简体   繁体   English

当父级重新渲染时,React 子级会更新 DOM

[英]Will React children update DOM when its parent rerender

i'm a bit confused with how React re-render.我对 React 如何重新渲染有点困惑。

const Parent = () => {
  const [ value, setValue ] = useState(0);

  return (

<div>
 <Child></Child>
 <button onClick={() =>setValue(value => value + 1)}>Set Value </button>
</div>

}

const Child = () => { 
   console.log('child rerender');
return (<div>Children</div>); 
}

so basically, when i click the button in Parent, the Parent re-render which lead to the rerender of Child component, and the console log chid rerender .所以基本上,当我单击 Parent 中的按钮时,Parent 重新渲染导致 Child 组件的重新渲染,以及控制台日志chid rerender

So my question is will the rerender of Child Component only means re-run the JS part ( console.log('child rerender') ), and the DOM of Child will stay the same ( without any DOM repaint and reflow)?所以我的问题是the rerender of Child Component重新渲染是否只意味着重新运行 JS 部分( console.log('child rerender') ),而 Child 的 DOM 将保持不变(没有任何 DOM 重绘和重排)? Or it actually unmount the Child and mount it again to DOM tree, even though its DOM content stay the same.或者它实际上卸载了 Child 并将其再次安装到 DOM 树,即使它的 DOM 内容保持不变。

Thanks谢谢

See the FAQ .请参阅常见问题解答

The function will run, the virtual DOM will be reconciled against the real DOM, and then the real DOM won't be updated because nothing will have changed. function 将运行,虚拟 DOM 将与真实 DOM协调,然后真实 DOM 将不会更新,因为没有任何变化。

You shouldn't need to care about whether React mounts and unmounts components (except in specific cases).您不需要关心 React 是否安装和卸载组件(特定情况除外)。 (You can force it to do so by changing a component's key .) (您可以通过更改组件的key来强制它这样做。)

In this case, I believe what happens to the concrete DOM is that as React does its VDOM<->DOM reconciliation, it notes that the structure of the DOM hasn't changed, nor have any text values (since the value isn't shown anywhere), so it does nothing to the concrete DOM.在这种情况下,我相信具体 DOM 发生的事情是,当 React 进行 VDOM<->DOM 协调时,它注意到 DOM 的结构没有改变,也没有任何文本值(因为value不是显示在任何地方),因此它对具体的 DOM 没有任何作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM