【问题标题】:Which renders first child or parent in reactjs在reactjs中呈现第一个孩子或父母
【发布时间】:2018-10-24 07:56:06
【问题描述】:
我是 reactjs 的初学者,并试图理解诸如父母和孩子在 reactjs 中呈现什么以及如何呈现的概念
从研究中我发现 react 先渲染孩子,然后渲染父母,但我无法得到有效的答案,如何以及为什么?如果孩子无法渲染会发生什么,我猜在 react 16 中有一个名为 componentDidCatch 的生命周期来处理如果孩子无法渲染,那么在 react 16 之前有什么以及我们如何处理这些场景
请帮帮我
【问题讨论】:
标签:
javascript
jquery
reactjs
redux
react-redux
【解决方案1】:
当componentDidMount 触发时,您可以进行 DOM 操作,因此父级仅在子级挂载后接收它是有意义的。也就是说,您可以使用componentWillMount,它向相反的方向触发,父母优先。
如果这很清楚,这就是您在 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/> 会被渲染!
【解决方案2】:
这取决于“孩子”和“渲染”的定义。
当子对象嵌套在父对象的render 中时,首先调用子对象的render 函数,因为父对象需要在自己的render 函数中使用子对象render 的结果。如果孩子是 children 道具,它也会首先呈现,因为父母需要将其作为 children 道具接收。
在这种情况下,'child' 是父元素 render 中的嵌套元素,首先渲染和安装子元素,Parent 中的错误边界将能够捕获来自 Child 的错误:
class Parent extends Component {
componentDidCatch() {}
render = () => <div><Child/></div>;
}
const Grandparent = props => <Parent/>;
在这种情况下,'child' 是 children 属性,首先渲染一个子级但未挂载,因为 children 未使用,Parent 中的错误边界将无法捕获来自Child 因为Child 实际上是在Grandparent 中渲染的:
class Parent extends Component {
componentDidCatch() {}
render = () => <div/>;
}
const Grandparent = props => <Parent><Child/></Parent>;
在 React 15 中,unstable_handleError lifecycle hook 用于创建错误边界并处理子级错误。在 React 16 中它被替换为 componentDidCatch。