【问题标题】:404 route issues with React Router and SuspenseReact Router 和 Suspense 的 404 路由问题
【发布时间】:2020-12-11 12:55:42
【问题描述】:

我正在尝试使用 React 16.12.0 中的延迟加载和 Suspense。我也在使用 React Router 5.1.2。

这是我第一次使用 Suspense,但我还没有找到合适的方法来加载 404/NoMatch 而不会导致其他问题。

我的代码如下所示:

import Component1 from 'path'
import Component2 from 'path'
import NoMatchPage from 'path'
const Component3 = lazy(()=>import('path'));
const Component4 = lazy(()=>import('path'));

<Router>
   <Switch>
        <Route exact path="/route-1" component={Component1}/>
        <Route exact path="/route-2" component={Component2}/>
        <Suspense fallback={<Loader/>}>
            <Route exact path="/route-3" component={Component3}/>
            <Route exact path="/route-4" component={Component4}/>
        </Suspense>
        <Route component={NoMatchPage}/>
   <Switch>
</Router>

  • 这样写,NoMatchPage 组件将永远不会显示。
  • 写在 Suspense 中,作为最后一个子节点,将在任何路由上渲染 NoMatchPage 组件,放置在应该在该路径上渲染的组件之后。
  • 写在 Suspense 上方,将在任何路径上渲染 NoMatchPage 组件,放置在应该在该路径上渲染的组件之前。

我查看了官方文档和很多实际示例,但没有发现任何可以帮助我解决此问题的内容。

【问题讨论】:

    标签: reactjs react-router lazy-loading react-suspense no-match


    【解决方案1】:

    从我读到的the official documentation,有一个例子,Switch 组件在 Suspense 组件中工作。因此,也许对于您的问题,您可以尝试将 Switch 组件移动到 Suspense 组件中(组件 Suspense 的顺序高于组件 Switch )。下面是一个例子。

      <Router>
        <Suspense fallback={<div>Loading...</div>}>
          <Switch>
            <Route exact path="/" component={Home}/>
            <Route path="/about" component={About}/>
          </Switch>
        </Suspense>
      </Router>
    

    祝你好运!

    【讨论】:

      【解决方案2】:

      也许你已经想通了,但是尝试像这样将悬念嵌套在路线中,并为每条你想有悬念后备的路线做这件事:

      <Route exact path="/route-3"/>
       <Suspense fallback={<Loader />}>
        <Component3/>
       </Suspense>
      </Route>
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-17
        • 2019-01-07
        • 1970-01-01
        • 2019-01-15
        • 2022-06-15
        • 2021-01-09
        • 2022-01-09
        相关资源
        最近更新 更多