为什么ReactJS错误边界会忽略子级属性

时间:2018-10-19 19:19:06

标签: reactjs

请参见下面的代码。

错误边界组件直接来自ReactJS在线示例。 我正在尝试将MyComponent用作功能组件。

问题是为什么错误边界没有显示“出了点问题”消息? 还有其他选择吗?或有关如何重构现有组件的任何参考?看来,代码永远不会到达componentDidCatch。

  class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null, errorInfo: null };
  }

  componentDidCatch(error, errorInfo) {
    // Catch errors in any components below and re-render with error message
    this.setState({
      error: error,
      errorInfo: errorInfo
    })
    // You can also log error messages to an error reporting service here
  }

  render() {
    if (this.state.errorInfo) {
      // Error path
      return (
        <div>
          <h2>Something went wrong.</h2>
          <details style={{ whiteSpace: 'pre-wrap' }}>
            {this.state.error && this.state.error.toString()}
            <br />
            {this.state.errorInfo.componentStack}
          </details>
        </div>
      );
    }
    // Normally, just render children
    return this.props.children;
  }  
}

const MyComp = ( { children } ) => {

  return (

     <div className='tile-h'>
       {children.l} // <-- this should fail and the component.
     </div>

  )

}
function App() {
  return (
    <div>
      <ErrorBoundary>
        <p>lorem ipsum</p>
        <MyComp><h2>test</h2></MyComp>
      </ErrorBoundary>
      <hr />

    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

0 个答案:

没有答案