Если условие для изменения маршрута с помощью React Router V4 - PullRequest
0 голосов
/ 27 сентября 2018

У меня есть два типа маршрутов, стран и контента:

  • / страны
  • / индустрия / рейтинг
  • / индустрия / аудитория
  • / веб-сайт / рейтинг
  • / веб-сайт / аудитория
  • / веб-сайт / конверсия

и т. д. *

Когда пользователь входит в приложениеЯ должен проверить, выбрал ли он уже страну, которую я сохраняю, используя localStorage .

Если у пользователя уже выбрана страна, ему нужно перейти на /промышленность / рейтинг , если нет - / страны .

Я получаю предупреждение об изменении маршрута с помощью кода:

<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>

Есть ли способ улучшить это, используя только маршруты для проверки моего состояния?

Спасибо!

1 Ответ

0 голосов
/ 27 сентября 2018

Вы можете просто написать собственный компонент, который отображает маршруты или перенаправления в страну, вместо условного отображения маршрутов, вызывающих это предупреждение

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...