反应.使用提供程序时抛出createContext错误



我正在尝试使用React上下文在typescript中的子组件中管理我的状态。但是,我目前面临以下代码的问题:

contexts/context.ts里面我有:

export const MyContext = React.createContext(null);

components/Parent.tsx里面我有:

import {MyContext} from '../contexts/context';
export default function Parent() {
const [state, setState] = React.useState([]);
const MyContextManager = React.useContext(MyContext);
return (
<MyContextManager.Provider value={[state, setState]}>
<Child />
</MyContextManager.Provider>
)  
}

在我的子组件中我有:

const [state, setState] = React.useContext(MyContext);
const handleState = (value) => {
setState(value);
}

然而,我目前得到一个错误:

TypeError: MyContextManager is null

你的意思是使用MyContext.Provider。查看文档

你还提到使用TypeScript,但TypeError是一个运行时错误。似乎TS认为你的MyContextManagerany型左右。或者TypeScript认为将null作为组件类型是可以的。

最新更新