错误边界与 Suspense
ErrorBoundary.jsx
export default class ErrorBoundary extends React.Component {
state = {
hasError: false
}
static getDerivedStateFromError(err){
return {
hasError: true
}
}
componentDidCatch(error, info){
console.log(error, info);
}
render(){
if(this.state.hasError) {
return <h1>This is a Error UI</h1>
}
return this.props.children;
}
}
test.jsx
export default class Test extends React.Component{
render(){
return (
<div>{data.title} This is a Test Component</div> // 这里出现错误
)
}
}
index.jsx
import ErrorBoundary from './ErrorBoundary.jsx'
const TestComponent = React.lazy(() => import('./test.jsx'));
class Loading extends React.Component {
render() {
return <div>Loading...</div>;
}
}
class App entends React.Component {
render(){
return ( // 错误边界与 Suspense 匹配的方式
<div>
<div>123</div>
<ErrorBoundary>
<React.Suspense fallback={<Loading/>}>
<TestComponent />
</React.Suspense>
</ErrorBoundary>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
)
命名导出
针对 lazy 只支持默认导出 default 导出的组件。那可以用命名导出,实则是 ES6 的方法。
Components.jsx
class Test1 extends React.Component {
render(){
return <h1>This is Test1</h1>
}
}
class Test2 extends React.Component {
render(){
return <h1>This is Test2</h1>
}
}
export {
Test1,
Test2
}
这时再建一个 jsx 用命名导出作来转换为 default 导出的组件
test1.jsx
export {
Test1 as default
} from './Component.jsx'
test2.jsx
export {
Test2 as default
} from './Component.jsx'
这样就能用 lazy 动态导入