reactの戻る機能でページの状態を保持する方法は?
ページの状態を保持するために、以下の方法を使用することができます。
- 「ルート」
- 申し訳ございませんが、日本語でのネイティブのパラフレーズは提供できません。
<Route exact path="/" component={Home} />
- スイッチ
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
- React Contextを使用してデータを共有します。状態を保持する必要があるデータはContextに保存し、状態を保持する必要があるコンポーネントではContext.Providerを使用してデータを提供し、他のコンポーネントは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>
);
}
}
上記の方法を使用すると、ページの状態が保持され、バック操作を行っても情報が保持されます。