【问题标题】:Keep the current page rendered until the new page is loaded with React.lazy and React.Suspense保持当前页面呈现,直到使用 React.lazy 和 React.Suspense 加载新页面
【发布时间】:2021-01-29 18:17:33
【问题描述】:

我正在使用 React 路由器根据特定的 url 呈现我的不同页面。不,我想使用React.lazy 延迟加载我所有的页面组件:

import React from "react";

import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

const Page = React.lazy(() => {
  return import("./Page");
});

const App = () => {
  return (
    <Router>
      <React.Suspense fallback={<div>Loading page...</div>}>
        <Switch>
          <Route exact path="/">
            <h1>Home</h1>
            <Link to="/page">Go to another page</Link>
          </Route>

          <Route path="/page" component={Page} />
        </Switch>
      </React.Suspense>
    </Router>
  );
};

export default App;

这项工作真的很好,但是当我转到/page 时,我所有的Home 都消失了,我只看到了备用Loading page... 组件(页面消失了,然后另一个页面很快出现,这让用户感到不安)。

这是React.Suspense 的默认行为,但在这种情况下,有没有办法让实际的主页在屏幕上呈现Loading page... 消息在顶部,当 @ 987654330@组件加载完毕,直接渲染替换首页?

【问题讨论】:

    标签: javascript reactjs react-router react-suspense react-lazy-load


    【解决方案1】:

    这目前只能在实验性Concurrent Mode 中实现。您必须等到它普遍可用后才能在生产站点中使用它。

    【讨论】:

    • 哦,好的,你能分享一个在实验模式下实现的例子吗? :)
    • @johannchopin 问题是并发模式涉及到使用useTransition()钩子,但是react-router目前不支持。
    • 好的,我明白了,我想我需要等待:p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 1970-01-01
    • 2017-09-04
    • 2022-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多