我试图在React+TS中创建一个上下文,它需要2个字符串数组并使用这些数组更新对象的状态。但我在setChoices返回语句中出现标题错字我无法解决它。你们能帮帮我吗?
代码:
import { createContext, useState } from 'react';
type GiftsType = {
choices: string[];
links: string[];
setChoices: (arr1: string[], arr2: string[]) => void;
};
export const GiftsContext = createContext<GiftsType>({
choices: [],
links: [],
setChoices: (arr1, arr2): void => {},
});
export function GiftsProvider({ children }) {
const [gifts, setGifts] = useState<GiftsType>({
choices: [],
links: [],
setChoices: (arr1, arr2) => void {},
});
return <GiftsContext.Provider value={{ ...gifts, setGifts }}>{children}</GiftsContext.Provider>;
}
修改代码:
type GiftsType = {
choices: string[];
links: string[];
setChoices: (arr1: string[], arr2: string[]) => void;
setGifts: React.Dispatch<React.SetStateAction<GiftsType>>
};
it will work.
你的问题在这里:
export function GiftsProvider({ children }) {
const [choices, setChoices] = useState<GiftsType>({
choices: [],
links: [],
setChoices: (arr1: string[], arr2: string[]) => void {}, // change the name
});
return <GiftsContext.Provider value={{ ...choices, setChoices }}> {children}</GiftsContext.Provider>;
}
您使用的名称与您的状态设置函数相同,并且在您使用的扩展操作符的值中,您将有两个setChoices,这是错误的。
您的GiftType
需要setGift
的功能。
你给提供者的值本质上是
{
choices: string[]
links: string[]
setChoices: (arr1: string[], arr2: string[]) => void
setGifts: React.Dispatch<React.SetStateAction<GiftsType>>
};
但是它在等待
{
choices: string[]
links: string[]
setChoices: (arr1: string[], arr2: string[]) => void
};
只需修改您的GiftType(名称中的类型是多余的,您可以将类型命名为Gift
)以包含此功能