reactjs 类型“undefined”的参数不能赋值给类型“number|日期

rhfm7lfc  于 2023-01-12  发布在  React
关注(0)|答案(3)|浏览(402)

我尝试转换从dateRange变量获取的数据,但遇到错误:Argument of type 'Date | undefined' is not assignable to the parameter of type 'number | Date'. Type 'undefined' is not assignable to type 'number | Date'。我的代码有什么问题?
//头文件
从..“/上下文/上下文”导入{ useContextState }
常量表头=()=〉{常量{日期范围,设置日期范围,设置打开日期,打开日期} =使用上下文状态()

return (
           <span onClick={() => setOpenDate(true)} className="cursor-pointer">
            {`${format(dateRange[0].startDate, "MM/dd/yyyy")} To ${format(dateRange[0].endDate, "MM/dd/yyyy")}`}
        </span>
                     
    </nav>
)
}

export default Header
// context.tsx file

import { createContext, Dispatch, SetStateAction, useContext, useState } from "react";
import { addDays } from 'date-fns';
import { Range } from "react-date-range";
import { format } from "date-fns";

export interface Range {
    startDate?: Date | undefined ;
    endDate?: Date | undefined;
    key?: string | undefined
}
interface IstateContext {
    openDate: boolean
    setOpenDate: Dispatch<SetStateAction<boolean>>
    dateRange: Range[]
    setDateRange: Dispatch<SetStateAction<Range[]>>
}

const initialState = {
    openDate: false,
    setOpenDate: () => false,
    dateRange: [{
        startDate: new Date(),
        endDate: new Date(),
        key: "selection",
    }],
    setDateRange: () => void{}

}

const StateContext = createContext<IstateContext>(initialState)

interface Childern {
    children: React.ReactNode
}

export const ContextProvider: React.FC<Childern> = ({ children }) => {
    const [openDate, setOpenDate] = useState<boolean>(false)
    const [dateRange, setDateRange] = useState<Range[]>([
        {
            startDate: new Date(),
            endDate: new Date(),
            key: "selection",
        },
    ])

    return (
        <StateContext.Provider value={{ dateRange, setDateRange, openDate, setOpenDate
        }}>
            {children}
        </StateContext.Provider>
    )
}
export const useContextState = () => useContext(StateContext)
h7appiyu

h7appiyu1#

如果我没理解错的话,你想把dateRange.0.startDate/endDate传递给format函数,但是值可能是未定义的,format不接受未定义的值。
使用类型保护可以检查未定义的值并处理这种情况。

const range = dateRange?.[0];
if (range?.startDate === undefined || range?.endDate === undefined) {
    return <span>Invalid range!</span>
}
return (
    <span onClick={() => setOpenDate(true)} className="cursor-pointer">
            {`${format(range.startDate, "MM/dd/yyyy")} To ${format(range.endDate, "MM/dd/yyyy")}`}
    </span>
)
dphi5xsq

dphi5xsq2#

检查“范围”。您已从“react-date-range”导入。并且您还创建了一个无法覆盖该属性的接口。
将第三行替换为代码并确认其是否有效。“添加了空值检查”{${format(dateRange[0]?.startDate, "MM/dd/yyyy")} To ${format(dateRange[0]?.endDate, "MM/dd/yyyy")}}

q35jwt9p

q35jwt9p3#

该问题可能是由于您试图在startDate和endDate属性设置为值之前对其进行格式化而导致的。
在最初呈现组件时,dateRange[0].startDate和dateRange[0].endDate未定义,因此尝试设置它们的格式时会出错。
我建议的解决方案是在格式化它们之前检查它们是否已定义:

import { useContextState } from '../context/context'
import { format } from "date-fns";
const Header = () => { 
  const { dateRange, setDateRange, setOpenDate, openDate } = useContextState()
  return (
    <nav>
      <span onClick={() => setOpenDate(true)} className="cursor-pointer">
        {typeof dateRange[0].startDate === "number" && dateRange[0].startDate !== undefined && 
         typeof dateRange[0].endDate === "number" && dateRange[0].endDate !== undefined && (
          `${format(new Date(dateRange[0].startDate), "MM/dd/yyyy")} To ${format(new Date(dateRange[0].endDate), "MM/dd/yyyy")}`
        )}
      </span>
    </nav>
  )
}
export default Header

编辑:****@Undo提到如果dateRange[0].startDate是0会怎样,这是一个有效的日期,但是如果它是0,JavaScript解释器会把0当作falsy =〉return false =〉格式函数不会被调用,所以我重写了我的答案

相关问题