React in data transfer is commonly used for data transfer via props, but we need to use some of the content of the entire page all the components, the use of props at this time if it layer by layer, then transfer over and over again than the cumbersome, how to solve this problem then react to provide a context
context to solve this problem. If the react-redux react a case where data transfer between the components is substantially not used in context.
React.createContext
const MyContext = React.createContext(defaultValue);
复制代码
Create a context object, when subscribed to react render a component of this context, he read in the context value from the Provider
The first parameter is the method defaultValue
parameters only after the component tree does not provide Provider
the use of the component, which can be individually test components becomes more convenient, note: the undefined value as Provider transfer assembly does not cause consumer use defaultValue.
Context.Provider
<MyContext.Provider value={/* some value */}>
复制代码
Each object contains a Context Provider component in the Provider 上有一个value
property, the property value will be subscription (subscription would say there are two ways to back) the context of the descendants of this component direct access, so you can avoid the deep-level components to deliver props the problem, and subscribe to the context of the assembly, when the context changes when the value of the release assembly will automatically re-render
Class.contextType
This is a method of content subscription context, the class static属性contextType
is set to create good before context
the object used in various components of the life cycle of the current this.context
access context
class MyClass extends React.Component {
componentDidMount() {
let value = this.context;
/* perform a side-effect at mount using the value of MyContext */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* render something based on the value of MyContext */
}
}
MyClass.contextType = MyContext;
复制代码
If you are using public class fields syntax
can be used
class MyClass extends React.Component {
static contextType = MyContext;
render() {
let value = this.context;
/* render something based on the value */
}
}
复制代码
Context.Consumer
Another way is to use the subscription context Comsumer
component, subcomponent Comsumer component is a function, the function of the first parameter is the value of the context, the return value must be an element to react
<MyContext.Consumer>
{value => /* render something based on the context value */}
</MyContext.Consumer>
复制代码
Reproduced in: https: //juejin.im/post/5cf7835ff265da1b5e72e270