這篇文章主要介紹React16中異常處理的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

異常處理
在 React 15.x 及之前的版本中,組件內(nèi)的異常有可能會影響到 React 的內(nèi)部狀態(tài),進而導(dǎo)致下一輪渲染時出現(xiàn)未知錯誤。這些組件內(nèi)的異常往往也是由應(yīng)用代碼本身拋出,在之前版本的 React 更多的是交托給了開發(fā)者處理,而沒有提供較好地組件內(nèi)優(yōu)雅處理這些異常的方式。在 React 16.x 版本中,引入了所謂 Error Boundary 的概念,從而保證了發(fā)生在 UI 層的錯誤不會連鎖導(dǎo)致整個應(yīng)用程序崩潰;未被任何異常邊界捕獲的異常可能會導(dǎo)致整個 React 組件樹被卸載。所謂的異常邊界即指某個能夠捕獲它的子元素(包括嵌套子元素等)拋出的異常,并且根據(jù)用戶配置進行優(yōu)雅降級地顯示而不是導(dǎo)致整個組件樹崩潰。異常邊界能夠捕獲渲染函數(shù)、生命周期回調(diào)以及整個組件樹的構(gòu)造函數(shù)中拋出的異常。
我們可以通過為某個組件添加新的 componentDidCatch(error, info) 生命周期回調(diào)來使其變?yōu)楫惓_吔纾?/p>
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}然后我們就可以如常使用該組件:
<ErrorBoundary> <MyWidget /> </ErrorBoundary>
componentDidCatch() 方法就好像針對組件的 catch {} 代碼塊;不過 JavaScript 中的 try/catch 模式更多的是面向命令式代碼,而 React 組件本身是聲明式模式,因此更適合采用指定渲染對象的模式。需要注意的是僅有類組件可以成為異常邊界,在真實的應(yīng)與開發(fā)中我們往往會聲明單個異常邊界然后在所有可能拋出異常的組件中使用它。另外值得一提的是異常邊界并不能捕獲其本身的異常,如果異常邊界組件本身拋出了異常,那么會冒泡傳遞到上一層最近的異常邊界中。
在真實地應(yīng)用開發(fā)中有的開發(fā)者也會將崩壞的界面直接展示給開發(fā)者,不過譬如在某個聊天界面中,如果在出現(xiàn)異常的情況下仍然直接將界面展示給用戶,就有可能導(dǎo)致用戶將信息發(fā)送給錯誤的接受者;或者在某些支付應(yīng)用中導(dǎo)致用戶金額顯示錯誤。因此如果我們將應(yīng)用升級到 React 16.x,我們需要將原本應(yīng)用中沒有被處理地異常統(tǒng)一包裹進異常邊界中。譬如某個應(yīng)用中可能會分為側(cè)邊欄、信息面板、會話界面、信息輸入等幾個不同的模塊,我們可以將這些模塊包裹進不同的錯誤邊界中;這樣如果某個組件發(fā)生崩潰,會被其直屬的異常邊界捕獲,從而保證剩余的部分依然處于可用狀態(tài)。同樣的我們也可以在異常邊界中添加錯誤反饋等服務(wù)接口以及時反饋生產(chǎn)環(huán)境下的異常并且修復(fù)他們。完整的應(yīng)用代碼如下所示:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}
render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h3>Something went wrong.</h3>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}
class BuggyCounter extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(({counter}) => ({
counter: counter + 1
}));
}
render() {
if (this.state.counter === 5) {
// Simulate a JS error
throw new Error('I crashed!');
}
return <h2 onClick={this.handleClick}>{this.state.counter}</h2>;
}
}
function App() {
return (
<div>
<p>
<b>
This is an example of error boundaries in React 16.
<br /><br />
Click on the numbers to increase the counters.
<br />
The counter is programmed to throw when it reaches 5. This simulates a JavaScript error in a component.
</b>
</p>
<hr />
<ErrorBoundary>
<p>These two counters are inside the same error boundary. If one crashes, the error boundary will replace both of them.</p>
<BuggyCounter />
<BuggyCounter />
</ErrorBoundary>
<hr />
<p>These two counters are each inside of their own error boundary. So if one crashes, the other is not affected.</p>
<ErrorBoundary><BuggyCounter /></ErrorBoundary>
<ErrorBoundary><BuggyCounter /></ErrorBoundary>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);以上是“React16中異常處理的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司行業(yè)資訊頻道!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站chinadenli.net,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
網(wǎng)頁題目:React16中異常處理的示例分析-創(chuàng)新互聯(lián)
鏈接分享:http://chinadenli.net/article14/cosede.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站、網(wǎng)站排名、網(wǎng)站制作、App設(shè)計、自適應(yīng)網(wǎng)站、虛擬主機
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容