Javascript 如何根据redux状态将不同的react组件绑定到相同的react路由器路由?
使用React、Redux和React router,我希望根据Redux状态将不同组件绑定到同一路由。例如: 假设组分A和组分B是反应组分 假设我有这个redux州Javascript 如何根据redux状态将不同的react组件绑定到相同的react路由器路由?,javascript,reactjs,redux,react-router,frontend,Javascript,Reactjs,Redux,React Router,Frontend,使用React、Redux和React router,我希望根据Redux状态将不同组件绑定到同一路由。例如: 假设组分A和组分B是反应组分 假设我有这个redux州 { flag: true; } 我想要这个反应路由器配置/routes.js <Route path="/" component={App}> <Route path="/test" component={ComponentA} /> </Route> 我知道我可以为Componen
{
flag: true;
}
我想要这个反应路由器配置/routes.js
<Route path="/" component={App}>
<Route path="/test" component={ComponentA} />
</Route>
我知道我可以为
ComponentA
和ComponentB
创建一个包装器组件,检查redux状态,然后呈现相应的组件,但我正在搜索一个不需要创建新组件的答案您可以在route的component字段中使用terinary操作符
<Route path="/test" component={flag ? ComponentA : ComponentB} />
编辑2:使用提供程序将React路由器连接到Redux
const Root = ({ store }) => (
<Provider store={store}>
<Router>
<Route path="/" component={App} />
</Router>
</Provider>
)
constroot=({store})=>(
)
如何从redux状态获取标志?这取决于项目的其余部分的外观,但一般情况下,您会使用连接HOC fromreact redux
并在mapStateToProps函数中将flag prop映射为参数。我在上面编辑了我的答案,以说明如何执行此操作。。
位于另一个文件中,因此基本上如果我执行flag代码>标志未定义如果要使用redux状态确定路由,则必须将其连接到某个位置。我不知道你的项目的架构,所以我不能告诉你在哪里做这个。只要将路由器
包装在提供商
组件中,您就应该可以访问redux商店。您应该有一些类似于我在第二次编辑中输入的内容,允许您访问路由处理程序中的状态。
import { connect } from 'react-redux';
// ... Component Definition
const mapStateToProps = (state, ownProps) => {
return {
flag: state.flag
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
// Whatever you want to dispatch
}
}
const ConnectedComponent = connect(
mapStateToProps,
mapDispatchToProps
)(YourComponent)
const Root = ({ store }) => (
<Provider store={store}>
<Router>
<Route path="/" component={App} />
</Router>
</Provider>
)