【问题标题】:Why aren't components being rendered according to route?为什么不根据路由渲染组件?
【发布时间】:2021-08-08 21:54:19
【问题描述】:

我正在使用 react 路由器,并且我创建了一个带有路径 /account 的路由,它呈现了 Account 组件。该组件呈现一个导航栏。在该导航栏下方,我希望它根据 URL 呈现不同的组件。如果 URL 是 account/edit 我想显示编辑帐户组件,如果 URL 是 account/myorders 我希望它显示我的订单组件,最后如果 URL 是 account/favorites 我希望它显示我下面的收藏夹组件导航栏,

  • 编辑帐户
  • 我的订单
  • 收藏夹

现在我遇到了这个问题,即 url 发生了变化,但在我的导航栏下方没有呈现任何组件。如果我在 /account 路由上使用确切路径,我会在路由 /edit/myorders/favorites 上得到“路径不存在”。如果我不在/account 路线上使用exact,则所有路线上都会显示相同的视图。只有当我得到一个组件来渲染时,如果我将例如/edit 的路由更改为/

function Routes() {
  return (
    <Switch>
      <Route path="/" component={Home} exact />

      <Route path="/account" component={Account} />

      <Route render={() => <Route component={Error} />} />
    </Switch>
  );
}

这些是导入到我的 App.js 组件中的现有路由

const Account = () => {
  return (
    <Router>
      <NavBar />
      <Switch>
        <Route path="/edit" component={EditAccount} exact />
        <Route path="/myorders" component={MyOrders} />
        <Route path="/favorites" component={Favorites} />
      </Switch>
    </Router>
  );
};

这些是我的 Account.js 组件中不起作用的路由

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom react-router-redux


    【解决方案1】:

    问题在于您使用&lt;Router&gt;&lt;/Router&gt;routes 包装在Acouunt 组件中。

    尝试删除它,像这样:-

    const Account = () => {
      return (
          <NavBar />
          <Switch>
            <Route path="/edit" component={EditAccount} exact />
            <Route path="/myorders" component={MyOrders} />
            <Route path="/favorites" component={Favorites} />
          </Switch>
      );
    };
    

    Check this answer 了解更多信息。

    【讨论】:

    • 这对我不起作用,但我找到了解决方案。这是使用嵌套路由。
    【解决方案2】:

    我的解决方案是使用这样的嵌套路由。

    const Account = () => {
      let match = useRouteMatch();
    
      return (
        <Router>
          <NavBar />
          <h1>Account</h1>
          <Switch>
            <Route path={`${match.path}/edit`} component={EditAccount} exact />
            <Route path={`${match.path}/myorders`} component={MyOrders} />
            <Route path={`${match.path}/favorites`} component={Favorites} />
          </Switch>
        </Router>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2020-11-06
      • 2018-12-25
      • 2019-12-17
      • 2016-12-19
      • 2020-05-25
      相关资源
      最近更新 更多