use*_*695 6 javascript reactjs next.js
如果子元素发生错误,我想在我的父反应组件上显示错误消息。
在这种情况下,错误将是捕获 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} />
)
}
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
要在我的 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>
}
}
Run Code Online (Sandbox Code Playgroud)
到我的_app.js文件。但我不确定这是否是要走的路……而且我不知道如何将错误归结为Component.
实现这一点的最佳方法是使用像redux或Fluxible这样的 React 状态管理。如果您正在使用 React 状态管理,那么您可以通过从 中调度消息child.js并连接到 中的 redux 存储来调用操作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 })}
/>
)
}
}Run Code Online (Sandbox Code Playgroud)
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)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2847 次 |
| 最近记录: |