React:如何使用 react-router 在视图之间共享状态?
React: how can you share the state between views using react-router?
我正在使用 react-router 路由到两个相互独立的视图。目前我一直在 Home
和 Backend
中使用新的状态对象,但我想摆脱它,因为它们都包含嵌套组件。
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route exact={true} path="/" component={Home} />
<Route path="/app/:user_id" component={Backend} />
</div>
</Router>
);
}
}
如何在不使用 redux 或 flux 等其他框架的情况下共享视图之间的状态?
将状态提升到您的 'App' 组件中,然后通过它们的 props 传递每个组件需要的任何状态元素。
例如,您在 App 中的状态可能如下所示:
App.state = {
homeRelatedStuff: {...},
backendRelatedStuff: {...},
sharedStuff: {...}
}
然后在声明要使用哪个组件时,传递 props:
<Route path={"/"} component={() => <Home homeStuff={this.state.homeRelatedStuff} sharedStuff={this.state.sharedStuff}/>}/>
*请注意,将组件列为函数的方法略有不同,因此您可以传递 props
你的状态不必像我一样将它们分开,它可能更平坦,你将多个道具传递给每个组件
我正在使用 react-router 路由到两个相互独立的视图。目前我一直在 Home
和 Backend
中使用新的状态对象,但我想摆脱它,因为它们都包含嵌套组件。
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route exact={true} path="/" component={Home} />
<Route path="/app/:user_id" component={Backend} />
</div>
</Router>
);
}
}
如何在不使用 redux 或 flux 等其他框架的情况下共享视图之间的状态?
将状态提升到您的 'App' 组件中,然后通过它们的 props 传递每个组件需要的任何状态元素。
例如,您在 App 中的状态可能如下所示:
App.state = {
homeRelatedStuff: {...},
backendRelatedStuff: {...},
sharedStuff: {...}
}
然后在声明要使用哪个组件时,传递 props:
<Route path={"/"} component={() => <Home homeStuff={this.state.homeRelatedStuff} sharedStuff={this.state.sharedStuff}/>}/>
*请注意,将组件列为函数的方法略有不同,因此您可以传递 props
你的状态不必像我一样将它们分开,它可能更平坦,你将多个道具传递给每个组件