[英]ReactJS: How to display an child component error in parent component
如果子元素發生錯誤,我想在我的父反應組件上顯示錯誤消息。
在這種情況下,錯誤將是捕獲 apollo 突變調用,例如您在 GrandChild 組件中看到的。
當然,我可以在父組件中創建一個函數,為錯誤設置一個狀態值,並將該函數傳遞給每個子組件、孫組件等等。 但由於我的結構有點復雜,這意味着要做很多工作。 這就是為什么我想到使用反應錯誤邊界。 但這是正確的用例嗎?
由於我使用的是 nextJS,每次throw Error
都會在開發模式下顯示錯誤堆棧跟蹤,因此不可能將錯誤顯示為消息
父.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
。
實現這一點的最佳方法是使用諸如redux或fluxible 之類的反應狀態管理。 如果您使用的反應狀態管理,那么你可以調用調度的動作從消息child.js
並連接到終極版在店里parent.js
很容易得到錯誤消息。
如果您決定使用您所描述的函數,您可以將一個函數傳遞給子級並讓子級調用該函數。
父.js
export class Parent extends Component { state = { error: null, } render () { return ( { /* if there is an error in any child component, it should be displayed here */ this.state.error && <Message>{this.state.error}</Message> } <Child {...props} defineError={(errMsg) => setState({ error: errMsg })} /> ) } }
GrandChild.js
import PropTypes from 'prop-types'; class GrandChild extends Component { static propTypes = { defineError: PropTypes.func, } doAnything () { return this.props.assumeToFail({ variables: { id: '123' } }).catch(error => { this.props.defineError(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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.