生命周期
- 类组件:构造,getDSfromProps, cDidMount,shouldCUpdate,cDidUpdate,cWillUnmounted....
- 函数组件:用 useEffect 代替 cDidMount,cDidUpdate,cWillUnmounted
错误边界
组件渲染错误是很常见的情况,错误发生时,不应该破坏整个应用。创建错误边界可避免应用在特定组件发生错误时中断。 错误边界是一个 React 组件,可以捕获子组件中的 JavaScript 错误。我们可以捕获错误、记录错误消息,并为 UI 组件故障提供回退机制。
-
有两种处理错误的方法
-
一种是生命周 期 componentDidCatch
-
一种是静态方法 static getDerivedStateFromError
-
请使用 static getDerivedStateFromError() 来渲染备用 UI,(控制 state
-
使用 componentDidCatch() 打印错误信息。上报
static getDerivedStateFromError(error) {
return { isError: true }; // 用于展示错误的 UI
}
componentDidCatch (err, info) {
console.log(err, info)
}