我正在尝试使用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认为你的MyContextManager
是any
型左右。或者TypeScript认为将null
作为组件类型是可以的。