【发布时间】: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 道具的 Apartment 和 House 给我这个错误:
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