官术网_书友最值得收藏!

Introduction to error boundaries

This is quite an overlooked feature that came with React version 16. As you should already know, JavaScript can throw errors. Such errors should not break your app, especially if it is from the financial sector. The regular imperative solution from JavaScript is a try-catch block:

try {
// helloWorld function can potentially throw error
helloWorld();
} catch (error) {
// If helloWorld throws error
// we catch it and handle gracefully
// ...
}

This approach is hard to use with JSX. Hence, the React team developed an alternative solution for React views. It's called Error Boundaries. Any class component can become an ErrorBoundary component, given that it implements the componentDidCatch function:

class AppErrorBoundary extends React.Component {
state = { hasError: false };

componentDidCatch() {
this.setState({ hasError: true });
}

render = () => (
this.state.hasError
? <Text>Something went wrong.</Text>
: this.props.children
)
}

export default () => (
<AppErrorBoundary>
<LoginForm />
</AppErrorBoundary>
)
If you follow along with these examples, you may see a red screen with an error nonetheless. This is a default behavior in development mode. You will have to dismiss the screen to see what the app looks like: the error boundary will work as expected. If you switch to release mode, the error screen will not appear.

LoginForm is now wrapped into ErrorBoundary. It catches any error that occurs while rendering LoginForm. If Error is caught, we display a short message stating that Something went wrong. We can get a real error message from the error object. However, it is not good practice to share it with the end user. Instead, send it to your analytics server:

// Chapter 2_View patterns/Example 11/ App.js
...
componentDidCatch
(error) {
this.setState({
hasError: true,
errorMsg: error
});
}

render = () => (
this.state.hasError
? (
<View>
<Text>Something went wrong.</Text>
<Text>{this.state.errorMsg.toString()}</Text>
</View>
)
: this.props.children
)
...
主站蜘蛛池模板: 商丘市| 蚌埠市| 宜丰县| 龙山县| 攀枝花市| 炉霍县| 福清市| 长岭县| 元谋县| 井冈山市| 焦作市| 扎鲁特旗| 肥乡县| 同心县| 巩义市| 临猗县| 甘洛县| 尚志市| 元谋县| 阿拉尔市| 和平区| 北海市| 柳河县| 绩溪县| 增城市| 西城区| 临海市| 潜江市| 威远县| 镇安县| 陵川县| 电白县| 武宁县| 大洼县| 新巴尔虎左旗| 淄博市| 淮南市| 凤山市| 谢通门县| 长宁区| 霍林郭勒市|