As we know, data passing in React is top-down (from parent to child), passing layer by layer through props. But if there are too many layers, it will be extremely tedious. Therefore, the Context Context is used to share data. This method does not need to be explicitly passed through props.
A,Context: To share global data with a component.
For example: current login user, theme, preferred language, etc.
- Context is used when many components at different levels need to access some of the same data.
- Careful use will lead to poor reusability.
const ThemeContext = React.createContext("light"); const App2 = () => { return ( <ThemeContext.Provider value="yellow"> <Toolbar /> </ThemeContext.Provider> ); }; const Toolbar = () => { return ( <div> <ThemeButton /> </div> ); }; Class ThemeButton extends react.ponent {// Specifies the contextType to read the current theme context. React will look up at the nearest theme Provider and use its value. // In this case, the current theme value is "yellow". static contextType = ThemeContext; // Use the static class attribute to initialize your contextType. render() { return <Button theme={this.context} />; }}Copy the code
const MyContext = React.createContext(defaultValue);
Copy the code
Create a Context object. When React renders a component subscribed to the Context object, the component reads the current Context value from the closest matching Provider in the component tree. The defaultValue parameter takes effect only if the component does not match the Provider in the tree.
Determine changes by detecting old and new values, using andObject.isSame algorithm.
< myContext. Provider value={variable} >Copy the code
- The Provider takes a value property and passes it to the consuming component, which can be one-to-many.
- When the value of the Provider changes, all consuming components that use it are rerendered.
- Mention value in State, otherwise rerendering of all consumers components will be triggered.
Wrong examples:
class App extends React.Component { render() { return ( <MyContext.Provider value={{something: 'something'}}> <Toolbar /> </MyContext.Provider> ); }}Copy the code
Correct way to write:
class App extends React.Component { constructor(props) { super(props); this.state = { value: {something: 'something'}, }; } render() { return ( <MyContext.Provider value={this.state.value}> <Toolbar /> </MyContext.Provider> ); }}Copy the code
In this paper, synchronous CSDN blog blog.csdn.net/aaqingying/… , the same author.