为什么 React Router 开关总是显示第一个组件?

Why React Router switch always showing first component?

我可以试试这个代码行;

// This code redirect to as "/" and it's work but example when ı write "/blabla" doesn't show Errorpage
<Switch>
       <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
            <Route exact path="/" component={Home} />
       </Suspense>
       <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
             <Route component={ErrorPage} />
       </Suspense>
 </Switch>

但它不会在页面上显示错误组件。 我发现了一件事,哪个在开关的顶部。它正在显示。 示例:

// Showing Home Component
<Switch>
      <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
        <Route exact path="/home" component={Home} />
      </Suspense>
      <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
        <Route component={ErrorPage} />
      </Suspense>
 </Switch>
// Showing ErrorPage component
        <Switch>
          <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
            <Route component={ErrorPage} />
          </Suspense>
          <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
            <Route exact path="/" component={Home} />
          </Suspense>
        </Switch>

Route 必须是 Switch 的直系子代。所以改为这样做。

<Switch>
  <Route exact path="/">
    <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
      <Home />
    </Suspense>
  </Route>
  <Route path="*">
    <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
      <ErrorPage />
    </Suspense>
  </Route>
</Switch>

开关的作用是当它匹配一条路线时它根本不会寻找任何其他组件。它将始终呈现第一个匹配项并且不会再看下去。基本上,它在调试代码时很有用。 我想在你的代码中,你必须定义一个额外的路径名来显示错误页面。 希望我的回答对您有所帮助。

你只能包装 1 个悬念,它也可以工作

试试下面的代码,看看是否有效

/ 将呈现主页和任何其他路由错误页面

<Switch>
       <Suspense fallback={<div>Daha sonra tekrar deneyin.</div>}>
         //anything wrong in this wrapped suspense will execute fallback
            <Route exact path="/" component={Home} />
            <Route path='/' component={ErrorPage} />
       </Suspense>
 </Switch>

将 home 路由放在其他所有路由下方,这样就可以了

        <Switch>


            <Route path="/about">
                <About />
            </Route>
            {/* <Route path="/users">
                <Users />
            </Route> */}
            <Route path="/demand">
                <Demand />
            </Route>
            <Route path="/">
                <Home />
            </Route>
        </Switch>