【问题标题】:React-Router <Switch> seem to have no effectReact-Router <Switch> 似乎没有效果
【发布时间】:2020-07-04 22:24:33
【问题描述】:
function App() {
  return (
    <>
      <CssBaseline />
      <Router>
        <Switch> 
          <Route path="/auth">
            <Auth></Auth>
          </Route>
          <Container>
            <Route path="/sign-in" component={SignIn} />
            <Route path="/home" component={Home} />
            <Route path="/load" component={Load} />
          </Container>
          <Route>
            <Redirect to="/sign-in"></Redirect>
          </Route>
        </Switch>
      </Router>
    </>
  );
}

&lt;Container&gt; 是一个上下文提供者。

export const Container = ({ children }: { children: JSX.Element[] }) => {
    return <AuthContainer.Provider>
        <DataContainer.Provider>
            {children}
        </DataContainer.Provider>
    </AuthContainer.Provider>
}

当位置在/ 时,&lt;Redirect&gt; 无效。 更改 &lt;Route&gt;to&lt;Route path="/" exact&gt;/ 中无效。 请告诉我原因,谢谢。

我将&lt;Container&gt;移到&lt;Switch&gt;之外,一切正常。但是为什么呢?

【问题讨论】:

  • 现在发生了什么?请提供更多详细信息。另外,我们可能需要查看Container的相关内容。如果它与基本路径“/”匹配,那么您可能永远不会到达您的重定向...
  • 我猜你需要使用exact 路径。试试this

标签: reactjs react-router


【解决方案1】:

Switch 会寻找完全匹配的,所以你需要为你的路由定义 path 属性,否则它永远不会匹配任何路由。

<Route path="/">
   <Redirect to="/sign-in"></Redirect>
</Route>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 2018-05-18
    • 1970-01-01
    • 2010-12-24
    • 2014-11-06
    • 2020-04-11
    相关资源
    最近更新 更多