How to maintain the page state when reverting in React?
To maintain the page state, you can use the following methods:
- The chosen path.
- identical
<Route exact path="/" component={Home} />
- Change the setting
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
- Utilize React Context to share data. Store the data that needs to be maintained in state in Context, and then use Context.Provider in the components that need to maintain state to provide the data. Other components can access the data through Context.Consumer.
const MyContext = React.createContext();
class MyProvider extends React.Component {
state = {
// 保存需要保持的状态数据
};
render() {
return (
<MyContext.Provider value={this.state}>
{this.props.children}
</MyContext.Provider>
);
}
}
class MyComponent extends React.Component {
render() {
return (
<MyContext.Consumer>
{context => (
// 使用 context 中的状态数据
)}
</MyContext.Consumer>
);
}
}
Using the above method, it is possible to preserve the page state even after performing a back operation.