在React中如何从子路由重定向到主路由

时间:2020-11-02 09:03:51

标签: javascript reactjs

我有一个关于反应路由器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`);
  };

0 个答案:

没有答案