为企业做网站电话开场白,小说网站的里面的搜索是怎么做的,专业网站建设常州,深圳鸿运通网站建设错误边界
React16增加防止某个组件的UI渲染错误导致整个应用崩溃子组件发生JS错误#xff0c;有备用的渲染UI错误边界是组件#xff0c;只能用class组件来写
错误边界组件捕获错误的时机
渲染时生命周期函数中组件树的构造函数中
getDerivedStateFromError
生命周期函数…错误边界
React16增加防止某个组件的UI渲染错误导致整个应用崩溃子组件发生JS错误有备用的渲染UI错误边界是组件只能用class组件来写
错误边界组件捕获错误的时机
渲染时生命周期函数中组件树的构造函数中
getDerivedStateFromError
生命周期函数 static getDerivedStateFromError(error)参数子组件抛出的错误返回值新的state渲染阶段调用作用不允许出现副作用异步代码、操作dom等
componentDidCatch
生命周期函数组件原型上的方法边界组件捕获异常并进行后续处理作用错误信息获取运行副作用在组件抛出错误后调用参数error抛出的错误、info组件引发错误相关的信息即组件栈
componentDidCatch(err, info) {console.log(componentDidCatch err, err)console.log(componentDidCatch info, info)
}无法捕获的场景
1.事件处理函数无法显示备用UI
function Correct() {const handleClick () {console.log(点击)throw new Error(click throw err)}return (div onClick{handleClick}正常显示内容/div)
}ErrorBoundaryCorrect /
/ErrorBoundary2.异步 setTimeout、ajax
function Correct() {const err () {setTimeout(() {throw new Error(抛出错误)}, 1000)}err()return (div正常显示内容/div)
}ErrorBoundaryCorrect /
/ErrorBoundary3.服务端渲染4.错误边界组件ErrorBoundary内部有错误
class ErrorBoundary extends React.Component {state {hasError: false,}static getDerivedStateFromError() {return {hasError: true}}render() {if (this.state.hasError) {return (h1This is Error UI{data}/h1)}return this.props.children}
}ErrorBoundaryTestErr /
/ErrorBoundary以上几种情况有可能导致整个React组件被卸载 示例代码
class ErrorBoundary extends React.Component {state {hasError: false,}static getDerivedStateFromError() {return {hasError: true}}render() {if (this.state.hasError) {return (h1This is Error UI/h1)}return this.props.children}
}
function TestErr() {return (h1{data}/h1)
}
function Correct() {return (div正常显示内容/div)
}
function App() {return (divErrorBoundaryTestErr //ErrorBoundaryCorrect //div)
}
ReactDOM.render(App /,document.getElementById(app)
)错误边界组件能向上冒泡
TestErr有错误冒泡到 ErrorBoundaryErrorBoundary自身也有错误如果多个嵌套错误边界组件 → 则从最里层错误触发、向上冒泡触发捕获
ErrorBoundary2ErrorBoundaryTestErr //ErrorBoundary
/ErrorBoundary2在开发模式下错误会冒泡至window而生产模式下错误不会冒泡详见文档
class ErrorBoundary2 extends React.Component {constructor(props) {super(props)window.onerror function (err) {console.log(window.onerror err, err)}}state {hasError: false,}static getDerivedStateFromError(err) {return {hasError: true}}render() {if (this.state.hasError) {return (h1This is Error UI2/h1)}return this.props.children}
}