我有一个背景:
export const AppConstArrays = createContext({
neededHours: [],
setNeededHours: (neededHours: INeededHours[]) => { },
serviceTypes: [],
setServiceserviceTypes: (serviceTypes:IServiceTypes[]) => { },
});我能够在数据服务中使用set函数,这是没有错误的。
ArraysState.setNeededHours(neededHours);
ArraysState.setServiceserviceTypes(services);当我尝试在其他地方使用它时,
export default function reCalc(index:number) { //This is not a function component?
const ArraysState = React.useContext(AppConstArrays);
}tslinter没有问题,但在运行时,我得到了令人讨厌的321 :-)
sp-webpart-workbench-assembly_en-us_8439e1230cb8ca442df6f89cf19f89a6.js:1 Uncaught Invariant Violation: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321
Hooks can only be called inside of the body of a function component说实话,我在任何地方都没有它的提供者,因为我在.ts文件中使用它--有什么帮助吗?谢谢yeAll
发布于 2020-06-23 01:19:41
当它在错误消息中声明在链接中时:
只能在函数组件的主体内调用钩子。
在这里,这意味着您不能在函数组件之外调用React.useContext。
您不应该在React组件之外的任何地方使用React上下文中的值。如果需要这样做,只需将它们作为输入参数从组件传递到这些函数(例如reCalc)。
例如,如果要在API调用函数中调用setNeededHours,可以如下所示:
function MyComponent() {
const { setNeededHours } = React.useContext(AppConstArrays)
React.useEffect(() => {
fetchSomething({ /* input data */ }, setNeededHours)
}, [])
return <div>Some Content</div>
}希望能帮上忙。
https://stackoverflow.com/questions/62524262
复制相似问题