javascript - 如果条件使用 React Router V4 更改路由
问题描述
我有两种类型的路线、国家和内容:
- /国家
- /行业/排名
- /行业/观众
- /网站/排名
- /网站/观众
- /网站/转换
ETC...
当用户进入应用程序时,我必须验证他是否已经选择了一个国家,我正在使用localStorage保存该国家。
如果用户已经选择了国家,他需要去/industry/ranking,如果没有,去/countries。
我收到有关通过代码更改路线的警告:
<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.
我的代码:
<Switch>
<Route exact path='/countries' component={Countries} />
{
current && (
<React.Fragment>
<Route exact path='/industry/ranking' render={() => <IndustryRanking country={current} />} />
<Route path='/industry/audience' render={() => <IndustryAudience country={current} />} />
<Route path='/website/ranking' render={() => <WebsiteRanking country={current} />} />
<Route path='/website/audience' render={() => <WebsiteAudience country={current} />} />
<Route path='/website/device' render={() => <WebsiteDevice country={current} />} />
<Route path='/website/conversion-orders' render={() => <WebsiteConversionOrders country={current} />} />
</React.Fragment>
)
}
{ !current ? <Redirect to='/countries' /> : <Redirect to='/industry/ranking' /> }
</Switch>
有没有办法只使用验证我的状况的路线来改善这一点?
谢谢!
解决方案
您可以简单地编写一个自定义组件来呈现路线或重定向到国家/地区,而不是有条件地呈现导致此警告的路线
const CustomRoute = (props) => {
const current = localStorage.getItem('country');
if(current) {
return <Route {...props} />
}
return <Redirect to='/countries' />
}
并像使用它一样
<Switch>
<CustomRoute exact path='/countries' component={Countries} />
<CustomRoute exact path='/industry/ranking' render={() => <IndustryRanking country={current} />} />
<CustomRoute path='/industry/audience' render={() => <IndustryAudience country={current} />} />
<CustomRoute path='/website/ranking' render={() => <WebsiteRanking country={current} />} />
<CustomRoute path='/website/audience' render={() => <WebsiteAudience country={current} />} />
<CustomRoute path='/website/device' render={() => <WebsiteDevice country={current} />} />
<CustomRoute path='/website/conversion-orders' render={() => <WebsiteConversionOrders country={current} />} />
<Redirect to='/industry/ranking' />
</Switch>
推荐阅读
- hyperledger-fabric - 关于 Hyperledger Explorer
- python - 如何使用 Pandas 匹配数据的顺序
- amazon-web-services - EKS - 来自多个 VPC/账户的工作节点
- php - 是否有理由不将我的管理目录放在 robots.txt 中?
- c# - 具有特殊值条件的分组导致Linq c#
- python - 为什么在这种情况下我需要调用“自我”?
- html - 如何使用javascript在单击按钮/图标时弹出一个窗口
- reactjs - 如何在onClick上连续获取值
- mysql - MySQL FORIEGN_KEY_CHECKS=1 默认情况下,但不工作
- deep-learning - 脉冲神经网络的文本输入