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

IT技术 javascript jquery reactjs redux react-redux
2021-05-22 12:19:48

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

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

请帮我

2个回答

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

如果这很清楚,这就是在 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: 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/>.

假设<ComponentWithErrors/>抛出错误,该组件unstable_handleError()将被调用并且状态将更新为error: true

当状态更新时,<SafeComponent/>而是呈现!

这取决于“子项”和“渲染”的定义。

孩子render当孩子被嵌套在父的功能是第一次调用render,因为父母需要使用儿童的结果render在自己的render功能。如果孩子是childrenprops,它也会首先呈现,因为父母需要将其作为childrenprops接收

在这种情况下,“子”是嵌套在父元素中的元素,render首先呈现并安装子元素,错误边界Parent将能够从Child以下位置捕获错误

class Parent extends Component {
  componentDidCatch() {}
  render = () => <div><Child/></div>;
}

const Grandparent = props => <Parent/>;

在这种情况下,“孩子”是childrenprops,首先呈现孩子但未安装,因为children未使用,错误边界Parent将无法从中捕获错误,Child因为Child实际上是在Grandparent

class Parent extends Component {
  componentDidCatch() {}
  render = () => <div/>;
}

const Grandparent = props => <Parent><Child/></Parent>;

在 React 15 中,unstable_handleError生命周期钩子用于创建错误边界并处理子级错误。componentDidCatch在 React 16 中被替换了