老师,错误边界是出现了,但是是在错误遮罩下面

来源:16-10 React.lazy与React.Suspense与错误边界

Panda_io

2023-06-03

图片描述

定义错误展示形式

import React, { Component } from 'react'

export default class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }
    static getDerivedStateFromError(error) {
        // 更新 state 使下一次渲染能够显示降级后的 UI
        console.log('error')
        return { hasError: true };
    }
    render() {
        if (this.state.hasError) {
            // 你可以自定义降级后的 UI 并渲染
            return <h1>Something went wrong.</h1>;
        }
        return this.props.children;
    }
}

设置错误边界

import React, { lazy, Suspense, useState, startTransition } from 'react'
import ErrorBoundary from './07_ErrorBoundary'
const Welcome = lazy(() => import('../components/Wellcome'))
const Welcome2 = lazy(() => import('../components/Wellcome2'))
export default function App() {
  const [show, setShow] = useState(true)
  const handleClick = () => {
    startTransition(() => {
      // 延后执行
      setShow(!show)
    })
  }
  return (
    <div>
      {/* 组件没有加载前就会显示loading */}
      <button onClick={handleClick}>点击</button>
      {/* 处理错误边界 */}
      <ErrorBoundary>
        <Suspense fallback={<div>loading</div>}>
          {show ? <Welcome /> : <Welcome2 />}
        </Suspense>
      </ErrorBoundary>

    </div>
  )
}

写回答

1回答

西门老舅

2023-06-03

这个错误的提示方式,是需要自己定义的,在错误边界的JSX中自己指定表现形式
0
3
Panda_io
回复
西门老舅
好的明白了谢谢老师!
2023-06-04
共3条回复

Vue3 + React18 + TS4入门到实战 系统学习3大热门技术

专为初级前端人员设计,系统性学习三大技术

261 学习 · 182 问题

查看课程