我有一个关于反应路由器dom的问题。在我的App.js
组件中,我有一些路由,其中包括:"/", "/:userId/profile", "/chat", ...
。 Profile.js
组件,其地址为"/:userId/profile"
。在那儿我又有一些路线来渲染一些页面(组件)。在所有路由的Profile.js
顶部,我设置了Header.js
组件,其中包含有关用户的信息,例如名称和图片,...。在Header.js
组件中,我有一个按钮,我想导航到"/:userId/create-post"
路由,并在App.js
组件中定义此路由。如何在App.js
中从嵌套路由重定向到主要路由?
在App.js
组件中:
export default function App() {
return (
<Router basename="/">
<Navigation />
<main className="app">
<Switch>
<Route path="/" exact render={() => <Posts />} />
<Route path="/:userId/profile" exact render={() => <Profile />} />
<Route path="/chat" exact render={() => <Chat />} />
<Route path="/suggested" exact render={() => <Suggested />} />
<Route path="/explore" exact render={() => <Explore />} />
<Route path="/auth" exact render={() => <Auth />} />
<Route
path="/:userId/create-post"
exact
render={() => <CreatePost />}
/>
<Redirect to="/" />
</Switch>
</main>
</Router>
);
}
在Profile.js
组件中:
const UserProfile = props => {
return (
<Section className="section">
<Router primary={false}>
<ProfileHeader user={props.user} />
<ProfileNavigate userId={props.user.userId} />
<Section className="section">
<Switch>
<Route
path="/:userId/profile/posts"
exact
render={() => <ProfilePostsList userPosts={props.userPosts} />}
/>
<Route
path="/:userId/profile/saved"
exact
render={() => <ProfileSavedList userPosts={props.userPosts} />}
/>
<Route
path="/:userId/profile/tagged"
exact
render={() => <ProfileTaggedList userPosts={props.userPosts} />}
/>
<Redirect
from={`/${props.user.userId}/profile`}
to={`/${props.user.userId}/profile/posts`}
/>
</Switch>
</Section>
</Router>
</Section>
);
};
export default UserProfile;
在Profile-Header.js
组件中:
<Button
className="weight btn-create"
onClick={navigateHandler}
>
Create Post
</Button>
事件处理程序:
const navigateHandler = () => {
history.push(`/${props.user.userId}/create-post`);
};