错误边界与 Suspense

ErrorBoundary.jsx

  1. export default class ErrorBoundary extends React.Component {
  2. state = {
  3. hasError: false
  4. }
  5. static getDerivedStateFromError(err){
  6. return {
  7. hasError: true
  8. }
  9. }
  10. componentDidCatch(error, info){
  11. console.log(error, info);
  12. }
  13. render(){
  14. if(this.state.hasError) {
  15. return <h1>This is a Error UI</h1>
  16. }
  17. return this.props.children;
  18. }
  19. }

test.jsx

  1. export default class Test extends React.Component{
  2. render(){
  3. return (
  4. <div>{data.title} This is a Test Component</div> // 这里出现错误
  5. )
  6. }
  7. }

index.jsx

  1. import ErrorBoundary from './ErrorBoundary.jsx'
  2. const TestComponent = React.lazy(() => import('./test.jsx'));
  3. class Loading extends React.Component {
  4. render() {
  5. return <div>Loading...</div>;
  6. }
  7. }
  8. class App entends React.Component {
  9. render(){
  10. return ( // 错误边界与 Suspense 匹配的方式
  11. <div>
  12. <div>123</div>
  13. <ErrorBoundary>
  14. <React.Suspense fallback={<Loading/>}>
  15. <TestComponent />
  16. </React.Suspense>
  17. </ErrorBoundary>
  18. </div>
  19. );
  20. }
  21. }
  22. ReactDOM.render(
  23. <App />,
  24. document.getElementById('app')
  25. )

命名导出

针对 lazy 只支持默认导出 default 导出的组件。那可以用命名导出,实则是 ES6 的方法。

Components.jsx

  1. class Test1 extends React.Component {
  2. render(){
  3. return <h1>This is Test1</h1>
  4. }
  5. }
  6. class Test2 extends React.Component {
  7. render(){
  8. return <h1>This is Test2</h1>
  9. }
  10. }
  11. export {
  12. Test1
  13. Test2
  14. }

这时再建一个 jsx 用命名导出作来转换为 default 导出的组件
test1.jsx

  1. export {
  2. Test1 as default
  3. } from './Component.jsx'

test2.jsx

  1. export {
  2. Test2 as default
  3. } from './Component.jsx'

这样就能用 lazy 动态导入