reactjs - 为什么 React 仍然渲染带有 Error Boundary 的子组件

标签 reactjs react-16

我将 React 16Error Boundary 功能结合使用: 配置文件.js

class Profile extends Component {
constructor(props) {
    super(props);
    this.state = {
        // user: {
        //     name: "Ha (Huck) H.K. NGUYEN"
        // }
        user: null
    };
    this.updateUser = this.updateUser.bind(this);
}

updateUser() {
    this.setState({ user: null })
}

render() {
    const { user } = this.state;
    console.log(user);
    return <div className="App">
            {user.name}
            <button onClick={this.updateUser}>
                Update
            </button>
        </div>
}
}

ErrorBoundary.js

class ErrorBoundary extends Component {
constructor(props) {
    super(props);
    this.state = {
        hasError: false
    }
}
componentDidCatch(error, errorInfo) {
    this.setState({ hasError: true });
}
render() {
    const { children } = this.props;
    const { hasError } = this.state;
    if (hasError) {
        return <HasError />
    }
    return children
}
}

App.js

class App extends Component {
render() {
    return <div className="App">
    <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <h1 className="App-title">Welcome to React</h1>
    </header>
    <ErrorBoundary>
        <Profile />
    </ErrorBoundary>
</div>
}
}

我看到功能组件在错误发生后仍然被调用并被捕获。任何人都可以解释为什么调用 render 函数。 enter image description here

不知道的可以看link的回答,您可以通过按 esc 键查看错误边界。

最佳答案

正如您在问题中提到的那样,按 Esc取消覆盖,你可以看到 ErrorBoundary消息和覆盖层的可见性仅限于开发环境。

您可以查看更多相关信息 here

至于render函数为什么执行,你要知道一旦render函数被执行并且您的代码抛出一个 RuntimeError,这是唯一一次 componentDidCatch你的方法ErrorBoundary .还有 create-react-app具有监听 RuntimeErrors 的功能正在生成并报告错误的根本原因,这就是您在叠加层中看到的内容。

要查看产生Overlay的相关代码,可以查看这个 github code

我希望我能回答你的问题。

关于reactjs - 为什么 React 仍然渲染带有 Error Boundary 的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51471005/

相关文章:

javascript - react : rendering components in a loop

javascript - 空获取时发出警报

reactjs - React.js + OpenCV.js ReferenceError:未定义cv

reactjs - react : reading data passed as parameter in history. 推送

javascript - Webpack react 热加载器不工作

javascript - 如何解决 react 原生 EventEmitter 监听器警告

javascript - 如何将参数传递给 usePromise React hook 内的 Promise

reactjs - 是否有 React Function 组件的类型,包括返回片段、空值、字符串等?

manifest - react 应用程序图标/ list 未显示在 gh-pages 上

javascript - 在 redux 的 React 16 中替换 componentWillRecieiveProps?