我正在学习如何使用componentDidCatch()
. 它看起来很直。它有效,但仍然显示完整的错误堆栈。
在单独的文件中:
import React, { Component } from 'react'
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false
}
}
componentDidCatch(error, info) {
console.log("Catching an error") // this is never logged
this.setState(state => ({...state, hasError: true }))
}
render() {
if (this.state.hasError) { return <div>Sorry, an error occurred</div> }
return this.props.children
}
}
export default ErrorBoundary
...
import React, { Component } from 'react'
class Foo extends Component {
render() {
return this.props.a.b; // So this should cause the error
}
}
export default Foo
...
import React, { Component } from 'react'
// Imported Foo and ErrorBoundary
class Home extends Component {
render() {
return <ErrorBoundary><Foo /></ErrorBoundary>
}
}
export default Home
在页面刷新时,我看到Sorry, an error occurred
了,从字面上看,一秒钟然后向用户显示完整的错误堆栈。这是 Create React App 的问题吗?我正在使用 React 16。