如何在渲染之外从 React Context Consumer 获取数据 [英] How to get the data from React Context Consumer outside the render

查看:26
本文介绍了如何在渲染之外从 React Context Consumer 获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the new React Context API and I need to get the Consumer data from the Context.Consumer variable and not using it inside the render method. Is there anyway that I can achieve this?

例如我想要的:

console.log(Context.Consumer.value);

到目前为止我测试的内容:上面的示例测试了 Context.Consumer currentValue 和 Context Consumer 拥有的其他变量,尝试将 Context.Consumer() 作为函数执行,但没有成功.

What I tested so far: the above example, tested Context.Consumer currentValue and other variables that Context Consumer has, tried to execute Context.Consumer() as a function and none worked.

有什么想法吗?

推荐答案

更新

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

Update

As of React v16.6.0, you can use the context API like:

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

然而,组件只能访问单个上下文.为了使用多个上下文值,请使用渲染道具模式.详细了解 Class.contextType.

However, the component can only access a single context. In order to use multiple context values, use the render prop pattern. More about Class.contextType.

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

If you are using the experimental public class fields syntax, you can use a static class field to initialize your contextType:

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

渲染道具图案

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

Render Prop Pattern

When what I understand from the question, to use context inside your component but outside of the render, create a HOC to wrap the component:

const WithContext = (Component) => {
  return (props) => (
      <CustomContext.Consumer>
           {value =>  <Component {...props} value={value} />}
      </CustomContext.Consumer>
  )
}

然后使用它:

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

这篇关于如何在渲染之外从 React Context Consumer 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆