[英]While using react-router 5 with redux 7 react-router <Link> is not resetting state after going to new route
[英]How to Bind different react components with the same react-router route depending on redux state?
使用React,Redux和React-router,我想根據redux狀態將不同的組件綁定到同一路由。 例如:
假設ComponentA和ComponentB是React組件
假設我有這個redux狀態
{
flag: true;
}
我想要這個React Router配置/routes.js
<Route path="/" component={App}>
<Route path="/test" component={ComponentA} />
</Route>
但如果我的Redux狀態下的flag
是false
我想擁有
...
<Route path="/test" component={ComponentB} />
...
我知道我可以創建一個ComponentA
和ComponentB
的包裝器組件來檢查redux狀態,然后渲染相應的組件,但我正在尋找一個不需要創建新組件的答案
您可以在路徑的組件字段中使用三元運算符。
<Route path="/test" component={flag ? ComponentA : ComponentB} />
編輯:這是你將國旗從你的國家映射到道具的方式。
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)
編輯2:使用Provider
將React Router連接到Redux
const Root = ({ store }) => (
<Provider store={store}>
<Router>
<Route path="/" component={App} />
</Router>
</Provider>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.