【问题标题】:React Router with Loadable Components error带有可加载组件错误的反应路由器
【发布时间】:2019-07-03 17:33:03
【问题描述】:

我已经创建了一个包含触发此错误的基本示例的存储库,以防有帮助:

loadable-components-ssr

我正在尝试在使用 react-router-dom 4.3.1loadable-component 5.6.0react-dom 16.8.1 的 SSR 设置中使用可加载组件

这是我尝试应用loadable-component 的组件示例:

import React from "react";

const About = () => <h2>About</h2>;

export default About;

这是在App 组件中导入的,如下所示:

import loadable from "@loadable/component";
...
const About = loadable(() => import("./About"));

并作为道具传递给同一App组件中的Route

<Route path="/about/" component={About} />

但我在开发者工具控制台中不断收到以下警告:

警告:失败的道具类型:提供给Routeobject类型的无效道具component,应为function

如果我使用first answer 中建议的替代语法:

<Route path="/about/" component={props => <About {...props} />} />

警告消失了,但是点击链接时到/about的路由仍然报错:

Uncaught Error: Loading chunk About failed.
(missing: http://localhost:3000/about/About.bundle.js)
    at HTMLScriptElement.onScriptComplete (VM1805 app.bundle.js:114)

我遵循了documentation关于在SSR中设置loadable-components的信息,所以我已经设置了客户端、服务器以及babel插件。

知道这里有什么问题吗?

【问题讨论】:

  • 可能是react路由器的问题,试试: } />
  • 修复了警告,但不幸的是,这样做仍然会在转到路由时加载About 组件产生错误(在本例中为/about):loadable.es.js:246 Uncaught Error: Loading chunk About failed.
  • 你能解决这个问题吗?我遇到了同样的错误
  • 很遗憾我没有,我可能会提供一个存储库的链接以便重现问题,以便更容易知道出了什么问题。
  • 我认为在客户端渲染中应该没问题。错误可能是因为您没有正确配置 ssr。

标签: reactjs babeljs react-router-v4 webpack-4 code-splitting


【解决方案1】:

这是known issue of react router

我认为您可以像这样编写路线:

<Route path="/about/" component={props => <About {...props} />} />

请谨慎使用此实现,因为重新渲染可能会出现一些错误行为。

【讨论】:

  • 修复了警告但路由(在此示例中为 /about)在使用此语法时仍然不起作用。
  • @rfc1484 你试过返回默认导入吗? import(“./About”).then(c =&gt; c.default)
  • 返回同样的错误:Loading chunk About failed.
【解决方案2】:

你为什么不使用react.lazy?它是官方组件。

const About = React.lazy(() => import('./About')
<Route exact path="/about" component={props => <About {...props} />} />

【讨论】:

  • React lazy 目前不支持服务端渲染:React.lazy and Suspense is not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we recommend Loadable Components. It has a nice guide for bundle splitting with server-side rendering.reactjs.org/docs/code-splitting.html
【解决方案3】:

这是你的“关于”组件:

import React from "react";

const About = () => <h2>About</h2>;

export default About;

你没有返回 jsx。这就是您收到错误的原因。
这就是你应该返回 jsx 的方式。

 const About = () => (<h2>About</h2>);

干杯!

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 2017-12-15
    • 2019-02-09
    • 2018-09-07
    • 2021-03-01
    • 2021-03-17
    • 2017-07-23
    • 2016-04-24
    相关资源
    最近更新 更多