如何从渲染之外的React Context Consumer获取数据

Gus*_*nça 16 reactjs react-context

我正在使用新的React Context API,我需要从Context.Consumer变量中获取Consumer数据,而不是在render方法中使用它.无论如何我能做到这一点吗?

例如,我想要的是:

console.log(Context.Consumer.value);
Run Code Online (Sandbox Code Playgroud)

到目前为止我测试的内容:上面的例子,测试了Context.Consumer currentValue和Context Consumer所拥有的其他变量,试图将Context.Consumer()作为一个函数执行而没有工作.

有任何想法吗?

Shu*_*tri 24

更新

React v16.6.0开始,您可以使用上下文API,如:

class App extends React.Component {
    componentDidMount() {
       console.log(this.context);
    }
    render() {
       // render part here
       // use context with this.context
    }
}
App.contextType = CustomContext
Run Code Online (Sandbox Code Playgroud)

但是,该组件只能访问单个上下文.要使用多个上下文值,请使用渲染道具模式.有关Class.contextType的更多信息.

如果您使用的是实验性公共类字段语法,则可以使用静态类字段初始化contextType:

class MyClass extends React.Component {
  static contextType = MyContext;
  render() {
    let value = this.context;
    /* render something based on the value */
  }
}
Run Code Online (Sandbox Code Playgroud)

渲染道具模式

当我从问题中理解,要在组件内使用上下文但在渲染之外,创建一个HOC来包装组件:

const WithContext = (Component) => {
  return (props) => (
      <CustomContext.Consumer>
           {value =>  <Component {...props} value={value} />}
      </CustomContext.Consumer>
  )
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

class App extends React.Component {
    componentDidMount() {
       console.log(this.props.value);
    }
    render() {
       // render part here
    }
}
export default WithContext(App);
Run Code Online (Sandbox Code Playgroud)

  • 这或多或少是来自https://reactjs.org/docs/context.html#accessing-context-in-lifecycle-methods的官方问题但是我发现这个解决方案比旧的`this.context`更复杂和样板反应15. (2认同)

Ank*_*dia 5

您可以使用useContextHook在功能组件中实现这一点。

您只需要从初始化它的文件中导入上下文。在这种情况下,DBContext.

 const contextValue = useContext(DBContext);
Run Code Online (Sandbox Code Playgroud)