【问题标题】:Bind slug like the first URL segment像第一个 URL 段一样绑定 slug
【发布时间】:2021-10-26 07:58:26
【问题描述】:

我正在开发使用 react-router-dom 的反应应用程序。我的应用程序行为异常。该应用程序没有主页。我们可以使用“slug”进入应用程序。例如:http://siteExample.net/my-subsite。如果 my-subsite 存在于我们的数据库中,我们需要处理这个 slug。 我的路线代码 sn-p:

const App = ({ isAuth, onSetSlug, slug}) => {

  useEffect(() => {
    onSetSlug(window.location.pathname.split('/')[1])
  }, [])

  return (
    <Router>
      <div className="App">
        <Suspense fallback={<Loading />}>
          <MainModal />
          <ScrollToTop>
            {!isAuth ? (
              <Switch>
                <Route path={'/:slug'} exact component={lazy(() => import('./containers/notAuth/home'))} />
                <ContentWrapper
                  container
                  component="main"
                  adaptSidebar={5}
                  adaptContent={7}
                >
                  <Switch>
                    <Route path={'/:slug/login'} exact component={lazy( () => import('./containers/notAuth/login'))} />
                    <Route path={'/:slug/signup'} exact component={lazy(() => import('./containers/notAuth/signup'))} />
                    <Redirect to={'/:slug'} />
                  </Switch>
                </ContentWrapper>
                <Redirect to={'/:slug'} />
              </Switch>
            </ScrollToTop>
          </Suspense>
        </div>
       </Router>
)}

例如,:slug/login 无法替代 my-subsite/login 的问题。顺便说一下,它仅适用于我的本地计算机。当我将它发布到远程主机时,它不能完全工作。

【问题讨论】:

  • 去掉内层Switch

标签: javascript reactjs routes react-router-dom


【解决方案1】:

删除外部/根路由上的 exact 属性,因为它必然会排除匹配的任何子路由。

<Switch>
  <Route
    path={'/:slug'} // <-- want this path prefix to match
    component={lazy(() => import('./containers/notAuth/home'))}
  />
    <ContentWrapper
      container
      component="main"
      adaptSidebar={5}
      adaptContent={7}
    >
      <Switch>
        <Route
          path={'/:slug/login'}
          exact
          component={lazy( () => import('./containers/notAuth/login'))}
        />
        <Route
          path={'/:slug/signup'}
          exact
          component={lazy(() => import('./containers/notAuth/signup'))}
        />
        <Redirect to={'/:slug'} />
      </Switch>
    </ContentWrapper>
  <Redirect to={'/:slug'} />
</Switch>

【讨论】:

  • 在这种情况下,它甚至不会将我推到新屏幕
  • @WhyAlwaysMe 什么 没有把你推到新屏幕?什么是新屏幕?你能说得更具体点吗?
猜你喜欢
  • 2021-09-17
  • 2011-04-20
  • 2015-04-17
  • 2023-03-04
  • 2019-03-20
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 2021-02-01
相关资源
最近更新 更多