在 reactjs 中呈现第一个孩子或父母

Tap*_*ave 6 javascript jquery reactjs redux react-redux

我是 reactjs 的初学者,并试图理解诸如父和子在 reactjs 中呈现什么以及如何呈现的概念

从研究中我发现反应首先呈现孩子然后是父母,但我无法获得有效答案如何以及为什么?以及如果孩子无法渲染会发生什么,我猜在 React 16 中有一个名为 componentDidCatch 的生命周期来处理如果孩子无法渲染,那么在 react 16 之前有什么以及我们如何处理这些场景

请帮我

Mos*_*ini 2

componentDidMount触发时,您可以进行 DOM 操作,因此父级仅在子级安装后才接收它是有意义的。也就是说,你可以使用componentWillMount相反方向的火,首先是父母。

\n\n

如果这一点很清楚,那么这就是在 React 16.x 中包装错误捕获的方式:

\n\n

React 16.x 错误处理示例\n

\r\n
\r\n
class ErrorBoundary extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n    this.state = { hasError: false };\r\n  }\r\n\r\n  componentDidCatch(error, info) {\r\n    // Display fallback UI\r\n    this.setState({ hasError: true });\r\n    // You can also log the error to an error reporting service\r\n    logErrorToMyService(error, info);\r\n  }\r\n\r\n  render() {\r\n    if (this.state.hasError) {\r\n      // You can render any custom fallback UI\r\n      return <h1>Something went wrong.</h1>;\r\n    }\r\n    return this.props.children;\r\n  }\r\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

\r\n
\r\n
<ErrorBoundary>\r\n  <MyWidget />\r\n</ErrorBoundary>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

参考:https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

\n\n

REACT 15 错误处理示例

\n\n

unstable_handleError()是所有组件的函数,当渲染或子渲染错误时调用。

\n\n

\r\n
\r\n
unstable_handleError: function(){\r\n  this.setState({error: "oops"})\r\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

\r\n
\r\n
class Boundary extends React.Component {\r\n      ...\r\n      unstable_handleError() {\r\n        logErrorSoYouCanFixTheThing()\r\n        this.setState({error: true});\r\n      }\r\n      render() {\r\n        if (this.state.error){\r\n          return <SafeComponent/>\r\n        } else {\r\n          return <ComponentWithErrors/>\r\n        }\r\n      }\r\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

安装时没有错误,因此它呈现<ComponentWithErrors/>

\n\n

假设<ComponentWithErrors/>抛出错误,unstable_handleError()将调用此组件\xe2\x80\x99s,并且状态将更新为error: true.

\n\n

当状态更新时,<SafeComponent/>会渲染 !

\n