【问题标题】:React 16: access context from outside of function componentReact 16:从函数组件外部访问上下文
【发布时间】:2020-05-25 15:24:04
【问题描述】:

我正在使用 React 16 并尝试使用 React 挂钩来访问上下文。

const { locale } = React.useContext(LocaleContext);

这个钩子调用是在 Redux 中间件中完成的。然后我得到错误 Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component.

我有什么方法可以从功能组件外部访问上下文吗?

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    不可能在 React 组件之外使用钩子。如果你真的需要访问 redux 中的语言环境,你可以在某处保留对它的外部引用:

    let globalLocale;
    
    // inside a component
    function MyComponent() {
      const {locale} = React.useContext(LocaleContext);
      globalLocale = locale;
    }
    

    或者您可以在 redux 中通过操作添加区域设置(在您的 LocaleContext 中,例如,每当它发生变化时):

    // inside LocaleContextProvider somewhere, when locale updates 
    dispatch({type: 'SET_LOCALE', payload: locale});
    

    您将能够像访问任何其他值一样在 redux 中访问它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 2022-11-02
      相关资源
      最近更新 更多