【问题标题】:Failed prop type: Invalid prop `component` of type `object` supplied to `Route`, expected `function`失败的道具类型:提供给“路线”的“对象”类型的无效道具“组件”,预期的“功能”
【发布时间】:2018-11-14 12:28:39
【问题描述】:

我刚刚将我的 React 应用程序更新到 16.6.0 并将 react-scripts 更新到 2.0.3 以开始使用惰性,并且在按照官方文档上的示例进行操作时出现此错误:

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

不管它,一切似乎都在工作,除了控制台中的这个错误。

这是我的一些代码:

// imports here
... 
const Decks = lazy(() => import('./pages/Decks'));
...
class App extends Component {
      ...

    render() {
        return (
            <ConnectedRouter history={history}>
                <div>
                    <MenuAppBar />

                    <div style={{paddingTop: '4rem'}}>
                        <Suspense fallback={<LazyLoading />}>
                            <Switch>
                                <Route exact path="/" component={Home} />
                                <Route path="/decks" component={Decks} />
                                ...
                            </Switch>
                        </Suspense>
                    </div>

                    <Footer />
                </div>
            </ConnectedRouter>
        );
    }

... }

我在这里做错了什么?

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    当使用延迟加载组件时,您需要将其提供给 Route 组件,例如

    // imports here
    ... 
    const Decks = React.lazy(() => import('./pages/Decks'));
    ...
    class App extends Component {
          ...
    
        render() {
            return (
                <ConnectedRouter history={history}>
                    <div>
                        <MenuAppBar />
    
                        <div style={{paddingTop: '4rem'}}>
                            <Suspense fallback={<LazyLoading />}>
                                <Switch>
                                    <Route exact path="/" component={Home} />
                                    <Route path="/decks" render={(props) => <Decks {...props} />} />
                                    ...
                                </Switch>
                            </Suspense>
                        </div>
    
                        <Footer />
                    </div>
                </ConnectedRouter>
            );
        }
    ... 
    }
    

    可能它在 react-router 中的 PropType 检查不正确,并且可能已在最新版本中修复以使其与 react v16.6 兼容

    【讨论】:

    • 谢谢,我会试试的。但我也注意到它无论如何都在工作,我在生产构建中没有看到那个错误。
    • 在生产构建中,PropType 警告无论如何都不会显示,只是 React 路由器中的 PropType 检查不会针对 16.6 版本的 react 进行更新
    • 您的建议确实有帮助。谢谢!
    • “懒惰”从何而来??
    • @Nibb,可以从 React 导入 Lazy。更新了答案
    【解决方案2】:

    将“react-router-dom”更新为“^4.4.0-beta.6”猫修复它。

    这是一个错误:https://github.com/ReactTraining/react-router/issues/6420#issuecomment-435171740

    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多