代码拆分
- Webpack-Code Splitting
- import import('./detail.js').then(...)
import React, { Component,lazy,Suspense } from 'react';
const About = lazy(()=>import(/* webpackChunkName:"about" */ './About'))
//ErrorBoundary 错误边界
//componentDidCatch
class App extends Component {
state={
hasError:false
}
// 和componentDidCatch效果等同
static getDerivedStateFromError(){
return{
hasError:true
}
}
// componentDidCatch(error,info){
// this.setState({
// hasError:true
// })
// }
render() {
const {hasError} =this.state
if(hasError){
return <div>Error</div>
}
return <div>
<Suspense fallback={<div>loading</div>}>
<About />
</Suspense>
</div>
}
}
export default App;
错误边界用法
class PotentialError extends React.Component { constructor(props) { super(props); this.state = { error: false }; } componentDidCatch(error, info) { this.setState({ error, info }); } render() { if (this.state.error) { return <h1>Error: {this.state.error.toString()}</h1>; } return this.props.children; } }
<PotentialError><AwesomeApp /></PotentialError>