Use redux/mobx to manage this. Context also provides a viable solution to this problem. Use redux/mobx to manage this problem.

First implementation effect:

After clicking the changeUser button:

Consider several steps to achieve this:

First, prepare components to share state:

// app.jsx import React from 'react'; import HomePage from "./page/HomePage"; Import {AppProvider} from "./store/appContext"; function App() { return ( <div className="App"> App <AppProvider> <HomePage name={1} /> </AppProvider> </div> ); } export default App;Copy the code

Second, create context, provide provider will need to share the state of the component outer package, provide consumer high-order components will need to consume the state of the component processing;

// appContext.js import React, { createContext, useReducer } from 'react'; const AppContext = createContext(); function AppProvider(props) { const initialState = { user: "Amy Tong" }; const reducer = (state, action) => { const { type, payload } = action; switch (type) { case "SET_USER": return { ... state, user: payload } default: break; } } const [state, dispatch] = useReducer(reducer, initialState) return ( <AppContext.Provider value={{ state, dispatch }}> {props.children} </AppContext.Provider> ) } const AppConsumer = Cmp => { return props => { return <AppContext.Consumer> {(ctx) => <Cmp {... props} {... CTX} />} </ appContext.consumer >} // or the following method can also be const AppConsumer = Cmp => {return props => {const CTX = useContext(AppContext); return <Cmp {... props} {... ctx} />; }; }; export { AppProvider, AppConsumer, AppContext };Copy the code

Fourth, use consumer in the HomePage component and get and modify the state value using props.

// HomePage.js import React from 'react'; Import {AppConsumer} from ".. /store/appContext"; function HomePage(props) { const { state, dispatch } = props; const changeUser = () => { dispatch({ type: "SET_USER", payload: "Mike" }) } return ( <div> homepage {JSON.stringify(state)} <button onClick={changeUser}>changeUser</button> </div> ) };  export default AppConsumer(HomePage);Copy the code

About the react context API use, see the document: react.docschina.org/docs/contex…