React 错误处理
React 错误处理
2023-09-14 08:59:53 时间
React 16 提供一个内置函数 componentDidCatch
,如果 render()
函数抛出错误,则会触发该函数。
举个例子
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 <h1>Something went wrong.</h1>; } return this.props.children; } }
当然你可以把这个组件封装下成为
<ErrorBoundary> <MyWidget /> </ErrorBoundary>
然后在顶部或任何地方,你可以这样使用它
另一个特性:
componentDidCatch
是包含错误堆栈的 info 对象!
{this.state.info && this.state.info.componentStack}
当然我是这么用的在路由
class App extends React.Component { constructor(props) { super(props) this.state = { hasError: false } } componentDidCatch(error, info) { console.log(error, info) this.setState({ hasError: true }) } render() { return this.state.hasError ? <h2>页面出错了404</h2> : ( <React.Fragment> {/* 检验是否有登录信息 */} <AutoRoute /> {/* 有了switch后,匹配到path后就不会再匹配下去了 */} <Switch> <Route path="/login" component={Login}></Route> <Route path='/register' component={Register}></Route> <Route path='/chat/:user' component={Chat}></Route> </Switch> </React.Fragment> ) } }
相关文章
- [React] Ensure all React useEffect Effects Run Synchronously in Tests with react-testing-library
- [React] Override webpack config for create-react-app without ejection
- [React] React.PureComponent
- [React Intl] Format Numbers with Separators and Currency Symbols using react-intl FormattedNumber
- [React Intl] Render Content with Placeholders using react-intl FormattedMessage
- [React] Create a Virtualized List with Auto Sizing Cells using react-virtualized and CellMeasurer
- [React] displayName for stateless component
- [React] Ensure all React useEffect Effects Run Synchronously in Tests with react-testing-library
- [React] Build a slide deck with mdx-deck using Markdown + React
- [React Intl] Install and Configure the Entry Point of react-intl
- [React] Create an Auto Resizing Virtualized List with react-virtualized
- [React] Radium: Updating Button Styles via Props
- [React + webpack] hjs-webpack
- React-Native 组件开发方法
- React的source code init时会自动检测Chrome dev tool的react extension装了没
- react学习笔记
- 观点 | Flutter vs React Native,两个开源框架如何选?
- 使用 React hooks 怎么实现类里面的所有生命周期?
- Taro React组件使用(4) —— RuiInputCode 验证码输入框