带有 React 16.6 Suspense 的 React Router “提供给 `Route` 的类型为 `object` 的无效道具 `component`,预期为 `function`." [英] React Router with React 16.6 Suspense "Invalid prop `component` of type `object` supplied to `Route`, expected `function`."

查看:16
本文介绍了带有 React 16.6 Suspense 的 React Router “提供给 `Route` 的类型为 `object` 的无效道具 `component`,预期为 `function`."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the latest version (16.6) of React with react-router (4.3.1) and trying to use code splitting using React.Suspense.

虽然我的路由正在工作并且代码确实分成了几个动态加载的包,但我收到了一个关于不返回函数的警告,而是一个对象到 Route.我的代码:

Although my routing is working and the code did split into several bundles loaded dynamically, I'm getting a warning about not returning a function, but an object to Route. My code:

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);

控制台警告如下:警告:道具类型失败:提供给`Route`的`object`类型的无效道具`component`,预期`function`.

正常的导入会返回一个函数,但是带有 lazy() 的动态导入会返回一个对象.

A normal import would return a function, but the dynamic import with lazy() is returning an object.

对此有任何修复吗?

推荐答案

尝试使用 render 属性代替 component

Try using render prop instead of component

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

这篇关于带有 React 16.6 Suspense 的 React Router “提供给 `Route` 的类型为 `object` 的无效道具 `component`,预期为 `function`."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆