日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

15 错误边界与使用技巧

發(fā)布時間:2023/12/10 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 15 错误边界与使用技巧 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

錯誤邊界

  • React16增加
  • 防止某個組件的UI渲染錯誤導致整個應用崩潰
  • 子組件發(fā)生JS錯誤,有備用的渲染UI
  • 錯誤邊界是組件,只能用class組件來寫

錯誤邊界組件捕獲錯誤的時機

  • 渲染時
  • 生命周期函數(shù)中
  • 組件樹的構(gòu)造函數(shù)中

getDerivedStateFromError

  • 生命周期函數(shù) static getDerivedStateFromError(error)
  • 參數(shù):子組件拋出的錯誤
  • 返回值:新的state
  • 渲染階段調(diào)用
  • 作用:不允許出現(xiàn)副作用(異步代碼、操作dom等)

componentDidCatch

  • 生命周期函數(shù)
  • 組件原型上的方法
  • 邊界組件捕獲異常,并進行后續(xù)處理
  • 作用:錯誤信息獲取,運行副作用
  • 在組件拋出錯誤后調(diào)用
  • 參數(shù):error(拋出的錯誤)、info(組件引發(fā)錯誤相關(guān)的信息,即組件棧)
componentDidCatch(err, info) {console.log('componentDidCatch err', err)console.log('componentDidCatch info', info) }

無法捕獲的場景

  • 1.事件處理函數(shù)(無法顯示備用UI)
function Correct() {const handleClick = () => {console.log('點擊')throw new Error('click throw err')}return (<div onClick={handleClick}>正常顯示內(nèi)容</div>) } <ErrorBoundary><Correct /> </ErrorBoundary>

  • 2.異步 setTimeout、ajax
function Correct() {const err = () => {setTimeout(() => {throw new Error('拋出錯誤')}, 1000)}err()return (<div>正常顯示內(nèi)容</div>) } <ErrorBoundary><Correct /> </ErrorBoundary>

  • 3.服務端渲染
  • 4.錯誤邊界組件(ErrorBoundary)內(nèi)部有錯誤
class ErrorBoundary extends React.Component {state = {hasError: false,}static getDerivedStateFromError() {return {hasError: true}}render() {if (this.state.hasError) {return (<h1>This is Error UI{data}</h1>)}return this.props.children} } <ErrorBoundary><TestErr /> </ErrorBoundary>

以上幾種情況有可能導致整個React組件被卸載

示例代碼

class ErrorBoundary extends React.Component {state = {hasError: false,}static getDerivedStateFromError() {return {hasError: true}}render() {if (this.state.hasError) {return (<h1>This is Error UI</h1>)}return this.props.children} } function TestErr() {return (<h1>{data}</h1>) } function Correct() {return (<div>正常顯示內(nèi)容</div>) } function App() {return (<div><ErrorBoundary><TestErr /></ErrorBoundary><Correct /></div>) } ReactDOM.render(<App />,document.getElementById('app') )

錯誤邊界組件能向上冒泡

  • TestErr有錯誤,冒泡到 ErrorBoundary,ErrorBoundary自身也有錯誤
  • 如果多個嵌套錯誤邊界組件 → 則從最里層錯誤觸發(fā)、向上冒泡觸發(fā)捕獲
<ErrorBoundary2><ErrorBoundary><TestErr /></ErrorBoundary> </ErrorBoundary2>

  • 在開發(fā)模式下,錯誤會冒泡至window,而生產(chǎn)模式下,錯誤不會冒泡,詳見文檔
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 (<h1>This is Error UI2</h1>)}return this.props.children} }

總結(jié)

以上是生活随笔為你收集整理的15 错误边界与使用技巧的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。