反应路由器没有达到重定向 [英] React router doesnt reach redirect

查看:52
本文介绍了反应路由器没有达到重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,上面有标签.当我导航到我的应用程序页面时,我推送到基础应用程序.IE./个人资料".

I have a page that has tabs on it. When I navigate to the page on my app I push to the base app. Ie. "/profile".

这是我的个人资料组件,即被调用的页面.

This is my profile component, the page that gets called.

<Profile>
      <Switch>
        <Route exact path={`${path}/feed`} component={Feed} />
        
       
        {profileId !== null && (
          <>
            <Route exact path={`${path}/friends`} component={Friends} />
            <Route exact path={`${path}/locations`} component={Locations} />
            <Route exact path={`${path}/blockedlist`} component={BlockedList} />
          </>
        )}
        <Redirect from={path} to={`${path}/feed`} />
      </Switch>
    </Profile>

重定向永远不会运行.当我删除检查 if profileId !== null 然后它工作.基本上,当我加载页面时,它将位于路径 /profile 然后该组件应在初始加载时处理到 /feed 的重定向.

The redirect never gets run. When I remove the check if profileId !== null then it works. Basically when I load the page it will be at path /profile then this component should handle the redirect to /feed on initial load.

推荐答案

如果你需要避免包装一个元素(就像这些 Route 的一样),你可以散布一个 JSX 元素数组,就像这样:

If you need to avoid wrapping an element (like with these Route's), you can spread an array of JSX elements instead, like this:

<Switch>
  <Route exact path={`${path}/feed`} component={Feed} />
  {...(profileId !== null ? [
    <Route exact path={`${path}/friends`} component={Friends} key='friends' />,
    <Route exact path={`${path}/locations`} component={Locations} key='locations' />,
    <Route exact path={`${path}/blockedlist`} component={BlockedList} key='blockedlist' />
  ]: [])}
  <Redirect from={path} to={`${path}/feed`} />
</Switch>

分解,这是做什么的:

{
  ...( // The spread operator will expand the array it's given into its components
    conditional ? // Check your condition
      [routes]: // If it's true, return the routes
      [] // If not, return no routes
  )
}

因为它将数组返回到渲染函数中,所以每个项目都应该有一个 key(反应使用它来优化重新渲染)所以我已经将每个路由设置为具有一部分它的路径名作为键,因为它们应该是唯一的.

Since it's returning an array into the render function, each item should have a key (Which is used by react to optimise the re-renders) so I've set each route to have part of it's path name as the key as these should be unique.

这篇关于反应路由器没有达到重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆