【发布时间】:2019-09-11 08:41:14
【问题描述】:
我有一个应用程序,我想在其中实现 reacts errorboundary:
import React, { Component } from 'react'
import ErrorView from './components/ErrorView'
class ErrorBoundary extends Component {
state = {
hasError: false,
}
static getDerivedStateFromError(error: any) {
// Update state so the next render will show the fallback UI.
return { hasError: true }
}
componentDidCatch(error: any, info: any) {
// Display fallback UI
this.setState({ hasError: true })
console.log('error', error)
console.log('info', info)
console.log('I have error')
// 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 <ErrorView />
} else {
return this.props.children
}
}
}
export default ErrorBoundary
我将我的应用程序放在错误边界内:
ReactDOM.render(
<ErrorBoundary>
<App />
</ErrorBoundary>,
document.getElementById('root')
)
在应用程序组件的其中一个子组件中,我创建了一个尝试映射空数组的组件。我这样做是为了得到一个错误,并希望能得到我的错误视图。
会发生什么: 我收到一个错误,errorView 被显示,但在我收到红框错误消息后一秒钟:
TypeError: 无法读取未定义的属性“地图”
这是在开发环境中,坦率地说,在我确认只有错误视图会显示之前,我害怕将其投入生产,
有没有办法抑制浏览器中的错误呈现? 我仍然在控制台中收到错误,我只是不希望它在浏览器渲染中。
【问题讨论】:
标签: javascript reactjs compiler-errors