【问题标题】:How to make react router replace component only after the matched route asynchronously loaded..?如何仅在匹配的路由异步加载后才使反应路由器替换组件..?
【发布时间】:2018-12-16 05:27:43
【问题描述】:

所以情况是这样的 - 当点击 Link 时,nprogress 栏将启动,我希望 react-router 仅在异步加载完成后将当前组件替换为匹配的路由......就像在 instagram 中一样......

但我只得到这个 -

这是我异步加载组件的 HOC --

import React, { useEffect, useState } from "react";
import nprogress from "nprogress";
import "nprogress/nprogress.css";

export default importComponent => props => {
  const [loadedComponent, setComponent] = useState(null);

  // this works like componentwillMount
  if (!nprogress.isStarted()) nprogress.start();

  if (loadedComponent) nprogress.done();

  useEffect(() => {
    let mounted = true;

    mounted &&
      importComponent().then(
        ({ default: C }) => mounted && setComponent(<C {...props} />)
      );

    // componentUnMount
    return () => (mounted = false);
  }, []);

  // return the loaded component
  const Component = loadedComponent || <div style={{ flexGrow: 1 }}>..</div>;
  return Component;
};

我在互联网上的任何地方都没有找到解决方案。所以我在 stackoverflow 中问这个问题。我希望这里有人可以解决这个问题。

【问题讨论】:

  • 任何代码示例?
  • 感谢您的回复....好的,我正在添加代码示例..
  • @AlexanderPoshtaruk 代码已添加
  • 你试过react-loadable吗?
  • 同样的事情...... react-loadable 的工作方式与我的 asyncLoad 相同

标签: reactjs react-router react-router-v4 react-router-dom code-splitting-async


【解决方案1】:

编辑:2021 年 11 月 15 日

旧方法不适用于使用路由参数或查询(例如 useLocation、useRouteMatch 等)的路由。

我现在使用的方法是使用 React.lazy、React.Suspense 并在呈现页面时更新 fallback 属性。因此,在加载下一页时,将显示与当前页面基本相同的组件实例的回退。此外,通过这种新方法,您可以随时呈现下一页;从后端获取数据后,或动画后等。

这是demosource code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 2018-09-14
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    相关资源
    最近更新 更多