ReactJS:如何在父组件中显示子组件错误

JavaScript React.js

LGil

2020-03-24

如果子元素发生错误,我想在我的父反应组件上显示错误消息。

在这种情况下,例如在GrandChild组件中看到的错误将是阿波罗突变调用的捕获。

当然,我可以在父组件中创建一个函数,该函数为错误设置状态值,并将该函数传递给每个子代,孙代等等。但是由于我的结构有点复杂,因此需要大量工作。这就是为什么我想到使用反应错误边界。但这是正确的用例吗?

当我使用nextJS时,每个人throw Error都会在开发模式下显示错误stacktrace,因此无法将错误显示为消息

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>
  }
}

to my _app.js file. But I'm not sure if this is the way to go... and I don't know how to get the error down to the Component.

第3662篇《ReactJS:如何在父组件中显示子组件错误》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android