问题描述
我有两种类型的路线,国家和内容:
I have two types of routes, countries and content:
- /国家
- /行业/排名
- /行业/受众
- /网站/排名
- /网站/观众
- /website/conversion
等等...
当用户进入应用程序时,我必须验证他是否已经选择了一个国家/地区,我正在使用 localStorage 保存该国家/地区.
When the user enters the application, I have to verify if he already chose a country, which I'm saving using localStorage.
如果用户已经选择了国家,他需要去/industry/ranking,如果没有,就去/countries.
If the user has the country already chosen, he needs to go to /industry/ranking, if don't, to /countries.
我收到一条关于通过代码更改路线的警告:
I'm receiving a warning about the route changing by code:
元素不应从受控变为不受控制(反之亦然).您最初提供了一个位置"道具,但在随后的渲染中省略了它.
我的代码:
<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>
有没有办法仅使用路线来验证我的状况来改善这一点?
Is there a way to improve this using just the routes to verify my condition?
谢谢!
推荐答案
您可以简单地编写一个自定义组件来呈现路线或重定向到国家/地区,而不是有条件地呈现导致此警告的路线
You can simply write a custom component that renders the Routes or redirects to the country instead of conditionally rendering the Routes which is causing this warning
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>
这篇关于如果条件使用 React Router V4 更改路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!