Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - React router doesnt reach redirect

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>

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All children of a <Switch> should be <Route> or <Redirect> elements. See the docs.

So, you can refactor your nested routes (in Profile component) like this:

function Profile() {
  const { path } = useRouteMatch()
  return (
    <Switch>
      <Route exact path={`${path}/feed`} component={Feed} />
      <Route
        render={(props) =>
          profileId !== null ? (
            <Switch>
              <Route exact path={`${path}/friends`} component={Friends} />
              <Route exact path={`${path}/locations`} component={Locations} />
              <Route exact path={`${path}/blockedlist`} component={BlockedList} />
            </Switch>
          ) : (
            <Redirect to={`${path}/feed`} />
          )
        }
      />
      <Redirect to={`${path}/feed`} />
    </Switch>
  )
}

Edit:

You can also add a redirect at last inside inner i.e. 2nd Switch above so that if user enter /profile and profileId is valid, it will redirect to /profile/friends:

...
<Redirect to={`${path}/friends`} />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...