可能你已經(jīng)知道, 在
React 16
中, 將會(huì)引進(jìn)一個(gè)全新的架構(gòu) -React Fiber
, 它徹底重寫了 React 的協(xié)調(diào)算法
, 并引入了一些新的特性
. 這篇文章就是跟大家分享 React 16 中新的生命周期方法 -componentDidCatch
, 它能捕獲在子組件樹中任何地方的 JavaScript 異常耿战,并打印這些錯(cuò)誤和展示備用UI
, 就像將children
包裹在一個(gè)大的try/catch
語(yǔ)句塊中. 你可以閱讀 Dan Abramov 的 Error Handling in React 16 獲取更多關(guān)于componentDidCatch
的內(nèi)容.
絕大多數(shù)的開發(fā)人員使用 React 16 都應(yīng)該是由 15 升級(jí)上來(lái)的, 然而, 為了使用錯(cuò)誤處理
而去重寫整個(gè)組件肯定是不明智的, 那么, 該怎么辦呢, 當(dāng)然有更好的處理方式, 那就是想辦法封裝組件
, 像修改組件定義
那是逼上梁上的行為.
那么, 錯(cuò)誤處理
究竟可以干些什么
- 當(dāng)有錯(cuò)誤發(fā)生時(shí), 我們可以友好地展示
fallback
組件 - 避免
normal
和fallback
組件耦合
- 我們可以清楚地發(fā)現(xiàn)某些
服務(wù)
的一些報(bào)錯(cuò)
- 我們可以復(fù)用
報(bào)錯(cuò)
和fallback
接下來(lái), 我們看一個(gè)最森破
的的實(shí)例
class ErrorHandler 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 <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// Then you can use it as a regular component
const MyPage = props => (
<Container>
<ErrorHandler>
<MyComponent />
<MyOtherComponent />
</ErrorHandler>
</Container>
)
其實(shí), 我們還可以將其優(yōu)化
一下, 比如將 ErrorHandler 參數(shù)化
, 將 reportErrorToService
作為 props
傳遞, 用 component
替代 上面返回的幾行視圖代碼
. 所以, 我們還是要更新我們的組件定義
, 以便將 UI
的一部分添加 ErrorHandler
中. 但正如我們之前所討論的, 我們并不想修改組件的定義, 我們只 decorate
它們
對(duì)此, 我們可以使用高階組件
const MyFallbackComponent = props => (
<h1>Something Went Wrong</h1>
)
// we'll talk about `withErrorHandler` later
const MyErrorHandler = withErrorHandler(
reportErrorToService,
MyFallbackComponent
)
const MyComponent = MyErrorHandler(props => (
/* ... */
))
const MyOthercomponent = MyErrorHandler(props => (
/* ... */
))
const MyPage = props => (
<Container>
<MyComponent />
<MyOtherComponent />
</Container>
)
我們可以使用 withErrorHandler HOC
來(lái)封裝組件, 使組件獲得錯(cuò)誤處理, 即當(dāng)錯(cuò)誤發(fā)生時(shí), 調(diào)用 reportErrorToService
并展示 fallback
組件, 從而, 我們帥氣地避免了大量組件的定義修改
然而, 我們還可以更帥氣. 當(dāng)服務(wù)報(bào)錯(cuò)跟 fallback
組件的視圖都基本相同時(shí), 我們可以像下樣一樣 export withErrorHandler HOC
import withErrorHandler from 'error-handler-hoc'
import reportErrorToService from '../services/errorReporter'
import FallbackView from '../components/Fallback/'
export default withErrorHandler(
reportErrorToService,
FallbackView
)
然后, 我們 export 封裝過(guò)后的組件
就可以了
// MyComponent.jsx
import ErrorHandler from '../HOCs/ErrorHandler.js'
const MyComponent = props => (
/* ... */
)
export default ErrorHandler(MyComponent)
// ====================
// MyOtherComponent.jsx
import ErrorHandler from '../HOCs/ErrorHandler.js'
import ...
const MyOtherComponent = props => (
/* ... */
)
// you might already be using HOCs
export default compose(
SomeOtherHOC,
ErrorHandler
)(MyOtherComponent)
// ====================
// MyPage.jsx
import { MyComponent, MyOtherComponent } from './components'
const MyPage = () => (
<Container>
<MyComponent />
<MyOtherComponent />
</Container>
)
這樣, 我們就可以輕松地給組價(jià)添加
錯(cuò)誤處理, 同樣, 我們也可以輕松地移除
那么, withErrorHandler
究竟是如何工作
的呢, 其實(shí), 實(shí)現(xiàn)它還是挺簡(jiǎn)單的
function withErrorHandler (errorCallback, FallbackComponent, Component) {
class WithErrorHandler extends React.Component {
constructor () {
super()
// Construct the initial state
this.state = {
hasError: false,
error: null,
errorInfo: null
}
}
componentDidCatch (error, info) {
// Update state if error happens
this.setState({ hasError: true, error, errorInfo: info })
// Report errors
errorCallback(error, info, this.props)
}
render () {
// if state contains error we render fallback component
if (this.state.hasError) {
const { error, errorInfo } = this.state
return (
<FallbackComponent
{...this.props}
error={error}
errorInfo={errorInfo}
/>
)
}
return <Component {...this.props} />
}
}
WithErrorHandler.displayName = `withErrorHandler(${Component.displayName})`
return WithErrorHandler
}
總結(jié)
這個(gè)高階組件
可以用來(lái)封裝任何組件, 捕獲所有異常, 你可以用其封裝整個(gè) page
, 也可以用其封裝個(gè)別組件
.
點(diǎn)擊該 repository 可以查看更多源碼
原文鏈接
: Catching exceptions using Higher Order Components in React 16