【发布时间】:2020-06-03 18:29:19
【问题描述】:
考虑以下场景-
每次点击按钮时,都会发生 setState,这将启动类组件 Main 的更新周期。这最终将导致渲染函数执行。在每次连续单击中,都会从父组件 Main 呈现一个新组件(如果在单击其 ComponentA 之前,则在单击之后它将是 ComponentB,反之亦然)。
根据 Reacts diffing 算法,如果从渲染返回的组件与前一次渲染的组件相同 (===),React 会通过与新的 diff 来递归地更新子树。如果它们不相等,则完全卸载前一个子树。
我的问题是,此示例中的 setState 是否实际上导致 Main 的安装周期而不是 update 或者它导致 Main 组件的更新周期但在其中,卸载 ComponentA 并安装 ComponentB (反之亦然,根据情况偶数或奇数)??
案例代码:
import React from "react";
import ReactDOM from "react-dom";
import {ComponentA, ComponentB} from './componets' // just for namesake
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {count: 0};
}
render() {
return (
<div>
<h1>Conditional rendering example in react</h1>
{(this.state.count)%2 == 0 ? (<ComponentA/>) : (<ComponentB/>)}
<button onClick={()=>{this.setState((state)=>({count:state.count+1}))}}
</div>
);
}
}
【问题讨论】:
标签: reactjs