[英]Typescript, useContext(), error: Argument of type 'never[]' is not assignable to parameter of type
I'm trying to use useContext() hook in typescript, but I expireance numerouse errores.我正在尝试在 typescript 中使用 useContext() 挂钩,但我遇到了许多错误。 useState initialy is equal to empty array of interface
Phone
which is imported, and then state and setState are passed in value
prop. useState initialy 等于导入的接口
Phone
的空数组,然后在value
prop 中传递 state 和 setState。
import { createContext, useState } from 'react';
import { Phone } from '../types/Phone';
type SetValue = (value: Phone[]) => void;
interface LikedContextInterface {
likedGadgets: Phone[];
setLikedGadgets: SetValue;
}
export const likedContext = createContext<LikedContextInterface>([]);
type Props = {
children: React.ReactNode;
};
export const LikedContextProvider: React.FC<Props> = ({ children }) => {
const [likedGadgets, setLikedGadgets] = useState<Phone[]>([]);
return (
<likedContext.Provider value={{ likedGadgets, setLikedGadgets }}>
{ children }
</likedContext.Provider>
);
};
in terminal I recieve following errors: Argument of type 'never[]' is not assignable to parameter of type 'LikedContextInterface'.
在终端中,我收到以下错误:
Argument of type 'never[]' is not assignable to parameter of type 'LikedContextInterface'.
Type 'never[]' is missing the following properties from type 'LikedContextInterface': likedGadgets, setLikedGadgets
Edited!!!已编辑!!!
So here is working code:所以这里是工作代码:
import { createContext, useState } from 'react';
import { Phone } from '../types/Phone';
type SetValue = (value: Phone[]) => void;
type LikedContextInterface = {
likedGadgets: Phone[];
setLikedGadgets: SetValue;
};
export const likedContext = createContext<LikedContextInterface>({
likedGadgets: [],
setLikedGadgets: () => {},
});
type Props = {
children: React.ReactNode;
};
export const LikedContextProvider: React.FC<Props> = ({ children }) => {
const [likedGadgets, setLikedGadgets] = useState<Phone[]>([]);
return (
<likedContext.Provider value={{ likedGadgets, setLikedGadgets }}>
{ children }
</likedContext.Provider>
);
};
You have to initialize context correctly by providing initial value which is LikedContextInterface:您必须通过提供 LikedContextInterface 的初始值来正确初始化上下文:
export const likedContext = createContext<LikedContextInterface>({
likedGadgets: [],
setLikedGadgets: (value: Phone[]) => {},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.