哪个在reactjs中呈现第一个孩子或父母 [英] Which renders first child or parent in reactjs

查看:137
本文介绍了哪个在reactjs中呈现第一个孩子或父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是reactjs的初学者,并试图理解类似的概念,如父级和子级如何在reactjs中渲染

i am beginner in reactjs,and trying to understand concept like what and how the parent and child renders in reactjs

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

from research i found that react renders the child first and then parent,but i could not able to get the valid answer how and why? and what happen if child fails to render,i guess in react 16 there is a lifecycle called componentDidCatch that handles if child fails to render,so what was there before react 16 and how we handle those scenario

请帮助我

推荐答案

在触发componentDidMount时,您可以进行DOM操作,这样,父级仅在挂载子级之后才接收它是有意义的.也就是说,您可以使用componentWillMount,它朝相反的方向射击,首先是父母.

When componentDidMount fires you can do DOM manipulation so it makes sense that parent only receives it after children are mounted. That said you can use componentWillMount which fires in the opposite direction, parents first.

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

If that is clear this is how you wrap error catching in React 16.x:

React 16.x错误处理示例

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

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

REACT 15错误处理示例

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

unstable_handleError() is a function for all components which is called when render or children render an error.

unstable_handleError: function(){
  this.setState({error: "oops"})
}

class Boundary extends React.Component {
      ...
      unstable_handleError() {
        logErrorSoYouCanFixTheThing()
        this.setState({error: true});
      }
      render() {
        if (this.state.error){
          return <SafeComponent/>
        } else {
          return <ComponentWithErrors/>
        }
      }
}

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

On mount there is no error, so it renders <ComponentWithErrors/>.

假设<ComponentWithErrors/>引发错误,则将调用此组件的unstable_handleError(),状态将更新为error: true.

Assuming the <ComponentWithErrors/> throws an error, this component’s unstable_handleError() will be called and state will update to error: true.

状态更新时,将呈现<SafeComponent/>

这篇关于哪个在reactjs中呈现第一个孩子或父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆