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`} />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…