【问题标题】:Nested route not rendering嵌套路由不渲染
【发布时间】:2020-05-15 17:58:11
【问题描述】:

会尽量简短。

仪表板组件正在渲染,但在点击localhost:3000/dashboard/shipments 时没有渲染。
不熟悉反应,不确定render={({ location })(Line 1) 是否引起问题。
尝试在Route (Line2) 中放置组件/仅使用 h4 标签,但没有任何效果。

已完成必要的导入。

App.js

const pages = [
  {
    pageLink: '/dashboard',
    view: Dashboard,
    displayName: 'Dashboard',
    showInNavbar: true,
    exact: false
  },....more routes.
return(
<Router>
  <Route render={({ location }) => (//---------->Line 1
    <React.Fragment>
      <Navbar />
      <Switch location={location}>
        {pages.map((page, index) => {
          return (
            <Route
              exact={page.exact}
              path={page.pageLink}
              component={page.view}
              key={index}
            />
          )
        })}
        <Redirect to='/' />
      </Switch>
    </React.Fragment>
  )}
  />
</Router>
)

dashboard.js

export default function Dashboard() {
    const authedUser = useSelector(state => state.authedUser);
    let { path } = useRouteMatch();
    if (!authedUser.loggedIn) return <Redirect to='/login' />
    return (
        <React.Fragment>
            <section id='dashboard-component'>
                <Sidebar />
                <Switch>
                    <Route exact path={path}>
                        <h2>Dashboard</h2>
                    </Route>
                    <Route exact path={`/${path}/shipments`}><h4>sdsd</h4></Route>//------>Line 2
                </Switch>
            </section>
        </React.Fragment>
    )
}

【问题讨论】:

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


    【解决方案1】:

    您在嵌套路线的开头有一个额外的/

    <Route exact path={`/${path}/shipments`}><h4>sdsd</h4></Route>
    

    现在path 已经返回/dashboard。编写 path={`/${path}/shipments`} 将使路由路径为 path={'//dashboard/shipments'}

    你需要指定你的子路由

    <Route exact path={`${path}/shipments`}><h4>sdsd</h4></Route>
    

    Working demo

    【讨论】:

    • 见鬼,我怎么会错过这个:(
    • 不用担心。这种东西最难发现
    猜你喜欢
    • 1970-01-01
    • 2017-06-07
    • 2017-11-15
    • 2019-01-12
    • 2022-01-13
    • 2017-09-19
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多