本文介绍了反应路由器惰性组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可行:
import Page from 'components/Page';
...
render() {
return (
<Route render={props => <Page {...props}/>}/>
);
}
但这不是:
import React, { lazy } from 'react';
const Cmp = lazy(() => import('components/Page'));
...
render() {
return (
<Route render={props => <Cmp {...props}/>}/>
);
}
反应16.8.6React Router 5.0.0
React 16.8.6React Router 5.0.0
我明白了:
The above error occurred in one of your React components:
in Unknown (at configured.route.js:41)
in Route (at configured.route.js:41)
in ConfiguredRoute (created by Context.Consumer)
...rest of stack trace
有人可以看到我在这里做什么愚蠢的事情吗?
Can anyone see what stupid thing I am doing here?
推荐答案
引用 在代码拆分中反应文档 ,建议将Suspense
与已定义的fallback
结合使用,以便在没有组件时可以使用某些内容代替组件没有加载.
Referencing the React Docs on code splitting, the recommendation is to use Suspense
with a defined fallback
so you have something to render in place of the components when they haven't loaded.
// Direct paste from https://reactjs.org/docs/code-splitting.html
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';
const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</Switch>
</Suspense>
</Router>
);
挂起应该是使用lazy
这篇关于反应路由器惰性组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!