【问题标题】:React.useContext and Minified React error #321;React.useContext 和 Minified React 错误 #321;
【发布时间】:2020-06-22 22:08:24
【问题描述】:

我有一个上下文:

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 文件中使用它 有什么帮助吗? 谢谢大家

【问题讨论】:

    标签: reactjs typescript react-hooks use-context


    【解决方案1】:

    正如它在错误消息中指出的in the link

    钩子只能在函数组件内部调用

    这里表示不能在函数组件之外调用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>
    }
    

    希望对你有帮助。

    【讨论】:

    • 谢谢,但没有。我有另一个在相同功能中运行良好的上下文。我将尝试将值移动到有效的上下文中并查看。无论如何感谢您的回答
    • 随时。是的,它可能会起作用(取决于它被调用的位置/方式),但它真的很脆弱,可能会引入像这样的意外问题。最好遵循标准做法以避免此类问题。
    猜你喜欢
    • 2020-03-27
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2023-02-24
    • 2020-02-26
    • 2020-05-11
    相关资源
    最近更新 更多