How to get the data from React Context Consumer outside the render

一个人想着一个人 提交于 2019-12-03 15:44:25

问题


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?

For examplify what I want:

console.log(Context.Consumer.value);

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.

Any ideas?


回答1:


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

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.

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 */
  }
}

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>
  )
}

and then use it:

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



回答2:


This is how it can be achieved.

 class BasElement extends React.Component {
  componentDidMount() {
    console.log(this.props.context);
  }

  render() {
    return null;
  }
}

const Element = () => (
  <Context.Consumer>
    {context =>
      <BaseMapElement context={context} />
    }
  </Context.Consumer>
)


来源:https://stackoverflow.com/questions/49870098/how-to-get-the-data-from-react-context-consumer-outside-the-render

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!