我希望在我的父级 react 组件中显示一个错误消息,如果子元素发生错误。
在这种情况下,例如在 GrandChild 组件中,错误会被捕获为 Apollo mutation 调用。
当然,我可以在父组件中创建一个函数来设置错误的状态值,并将该函数传递给每个子元素、孙子元素等。但是,由于我的结构有点复杂,这意味着需要做很多工作。这就是为什么我考虑使用 react 错误边界。但这是正确的用例吗?
由于我正在使用 nextJS,每个 throw Error 都会在开发模式下显示一个错误堆栈跟踪,因此不可能将错误显示为消息。
Parent.js
为了在我的NextJS应用程序中使用错误边界,我只需要添加_app.js。
在这种情况下,例如在 GrandChild 组件中,错误会被捕获为 Apollo mutation 调用。
当然,我可以在父组件中创建一个函数来设置错误的状态值,并将该函数传递给每个子元素、孙子元素等。但是,由于我的结构有点复杂,这意味着需要做很多工作。这就是为什么我考虑使用 react 错误边界。但这是正确的用例吗?
由于我正在使用 nextJS,每个 throw Error 都会在开发模式下显示一个错误堆栈跟踪,因此不可能将错误显示为消息。
Parent.js
export class Parent extends Component {
render () {
return (
{ /* if there is an error in any child component, it should be displayed here */
this.props.error &&
<Message>{error}</Message>
}
<Child {...props} />
)
}
}
GrandChild.js
class GrandChild extends Component {
doAnything () {
return this.props.assumeToFail({
variables: { id: '123' }
}).catch(error => {
console.error(error) // <-- this error should be given back to parent
throw new Error('fail') // <-- should I throw the error or call a custom function?
})
}
render () {
return (
<Button onClick={this.doAnything().bind(this)}>anything</Button>
)
}
}
export default graphql(exampleMutation, { name: 'assumeToFail' })(GrandChild)
为了在我的NextJS应用程序中使用错误边界,我只需要添加_app.js。
class MyApp extends App {
componentDidCatch (error, errorInfo) {
console.log('CUSTOM ERROR HANDLING', error)
// How do I get the error down to 'Component' in render()?
super.componentDidCatch(error, errorInfo)
}
render () {
const { Component, pageProps, apolloClient } = this.props
return <Container>
<ApolloProvider client={apolloClient}>
<Component {...pageProps} />
</ApolloProvider>
</Container>
}
}
我想把它加到_app.js文件中。但我不确定这是否是正确的方法……而且我不知道如何将错误缩小到Component
。
componentDidCatch
https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html - quirimmocomponentDidCatch
,但这会导致在开发模式下始终显示堆栈跟踪,因此我无法在组件中显示错误。 - user3142695componentDidCatch
只是其中的一部分,您还需要创建一个实现componentDidCatch
的错误边界组件,以便它可以返回一些错误状态,并基于该状态返回一个回退组件。请参见 https://reactjs.org/docs/error-boundaries.html 。请注意,它会转储全屏堆栈跟踪 "模态",右上角有一个 "X" 用于关闭它并返回到您的应用程序。 - Drew Reese