【问题标题】:Union type of two different useState setter functions gives error两个不同的 useState setter 函数的联合类型给出错误
【发布时间】:2022-11-18 02:17:42
【问题描述】:

我有两个不同的组件,在它们的状态下有一个共同的道具,在这个最小的例子中,它将是 pictures 道具,它是一个字符串数组:

公寓.ts

type ApartmentType = {
    landlord: string;
    pictures: string[];
}

function Apartment () {
    const [ apartmentData, setApartmentData ] = useState<ApartmentType>({
        landlord: 'juan',
        pictures: [ 'url1', 'url2' ]
    })

    return (
        <h1>Apartment</h1>
        <FileUploader setFunction={setApartmentData} />
    )
}

房子.ts

type HouseType = {
    owner: string;
    pictures: string[];
}

function House () {
    const [ houseData, setHouseData ] = useState<HouseType>({
        owner: 'Jhon',
        pictures: [ 'url1', 'url2' ]
    })

    return (
        <h1>House</h1>
        <FileUploader setFunction={setHouseData} />
    )
}

如您所见,我正在添加一个 FileUploader 组件,它将使用 useState 钩子附带的 set 函数更新其父级的 pictures 数组:

type FileUploaderProps = {
    setFunction: React.Dispatch<React.SetStateAction<HouseType> | React.SetStateAction<ApartmentType>>
}

function FileUploader ({ setFunction }: FileUploaderProps) {
    function updatePictures () {
        setFunction((prevValue: any) => ({ ...prevValue, pictures: [ ...prevValue.pictures, 'newUrl1', 'newUrl2'] }))
    }

    return (
        <div>
            <h1>File Uploader</h1>
            <button type='button' onClick={updatePictures}></button>
        </div>
    )
}

但是这里是问题出现的地方,FileUploader TS 中的 setFunction 道具的 ApartmentHouse 给我这个错误:

Type 'Dispatch<SetStateAction<HouseType>>' is not assignable to type 'Dispatch<SetStateAction<ApartmentType> | SetStateAction<HouseType>>'.
  Type 'SetStateAction<ApartmentType> | SetStateAction<HouseType>' is not assignable to type 'SetStateAction<HouseType>'.
    Type 'ApartmentType' is not assignable to type 'SetStateAction<HouseType>'.
      Property 'owner' is missing in type 'ApartmentType' but required in type 'HouseType'

我做错了什么?,我虽然在 FileUploader 中输入 setFunction 道具为:

React.Dispatch<React.SetStateAction<HouseType> | React.SetStateAction<ApartmentType>>

足以说明这两种可能性,但事实并非如此。

这是游乐场的link

【问题讨论】:

    标签: reactjs typescript react-hooks union-types


    【解决方案1】:

    您在“错误”位置(React.SetStateAction&lt;Apartment&gt;React.SetStateAction&lt;House&gt;)混淆了模板类型和联合类型。最好将函数设为 Union 类型,例如:

    type FileUploaderProps = {
        setFunction: React.Dispatch<React.SetStateAction<House>> | React.Dispatch<React.SetStateAction<Apartment>>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 2020-10-11
      • 2022-08-12
      相关资源
      最近更新 更多