【问题标题】:React Router with React 16.6 Suspense "Invalid prop `component` of type `object` supplied to `Route`, expected `function`."带有 React 16.6 Suspense 的 React Router “提供给 `Route` 的类型为 `object` 的无效 prop `component`,预期为 `function`。”
【发布时间】:2019-03-31 03:58:43
【问题描述】:

我正在使用最新版本 (16.6) 和 react-router (4.3.1) 的 React,并尝试使用 React.Suspense 进行代码拆分。

虽然我的路由工作正常,并且代码确实拆分为几个动态加载的包,但我收到了一个警告,提示我不返回函数,而是返回 Route 的对象。我的代码:

import React, { lazy, Suspense } from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';

import Loading from 'common/Loading';

const Prime = lazy(() => import('modules/Prime'));
const Demo = lazy(() => import('modules/Demo'));

const App = () => (
  <Suspense fallback={<Loading>Loading...</Loading>}>
    <Switch>
      <Route path="/" component={Prime} exact />
      <Route path="/demo" component={Demo} />
    </Switch>
  </Suspense>
);

export default withRouter(App);

控制台警告如下: Warning: Failed prop type: Invalid prop `component` of type `object` supplied to `Route`, expected `function`.

正常的导入会返回一个函数,但使用lazy() 的动态导入会返回一个对象。

有什么解决办法吗?

【问题讨论】:

标签: reactjs react-router react-router-v4 dynamic-import react-16


【解决方案1】:

尝试使用render 属性而不是component

<Route path="/" render={()=> <Prime />} exact />
<Route path="/demo" render={()=> <Demo />} />

【讨论】:

  • 谢谢!解决方案:&lt;Route exact path="/" component={props =&gt; &lt;Prime {...props} /&gt;} /&gt;
  • ronnyrr 的解决方案对我有用。另外,我更新到最新版本的 React 和 React 路由器(react-dom 16.6.3 - react-router-dom 4.3.1)
  • 这不是一个好的解决方案,因为如果您的 redux 连接在层次结构中高于此,它将导致不断卸载和重新安装这些组件。
  • 所以最好的办法是:javascript &lt;Route exact path="/" render={props =&gt; &lt;Prime {...props} /&gt;} /&gt; 在这种情况下,你在组件内部也收到了props
  • 使用内联箭头函数作为component prop 的参数将导致每次路由更改时重新渲染,如果您在渲染的子组件中嵌套路由并中继生命周期方法,这可能会出现问题。我会改用@tmvnty 解决方案。
【解决方案2】:

这将在react-router-dom 4.4+ 版本中得到修复,正如issue 所建议的那样

您可以等待最终版本,或者如果您今天不想更改代码, 您现在可以通过yarn add react-router-dom@next 安装测试版

【讨论】:

  • 我可以确认react-router-dom v5.0.0 解决了这个问题。 v4.4.x 似乎只在 v5.0.0 主要版本之前是 beta 版本。
【解决方案3】:

我知道这个答案没有回答原始问题,但由于我遇到过类似的问题,也许我的解决方案会帮助其他人。

我的错误:

Failed prop type: Invalid prop `component` of type `object` supplied to "link", expected function.

与接受的答案一样,这可以通过以下方式解决:

<Link to={'/admin'} title={'Log In'} component={props => <Button {...props} />} />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 2019-06-14
    • 1970-01-01
    • 2018-01-23
    • 2016-03-01
    • 2020-08-01
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多