简体   繁体   English

如果 props 和 state 没有改变,为什么 React 组件会更新

[英]Why does React component update if props and state didn't change

A React Copmponent is rendering when its state or propr remain the same.当 React 组件的 state 或 propr 保持不变时,它正在渲染。 I don't get why it does it rerender/update since the result wouldn't change我不明白为什么它会重新渲染/更新,因为结果不会改变

class A extends Component {
  render() {
    console.log("Hello")
    return "Foo";
  }
}
class App extends Component {
  constructor(props) {
    super(props);

    this.state = { a: "ASDA" };
  }

  render() {
    return (
      <div>
        <button onClick={()=>this.setState({a: Math.random()}) }>asdsa</button>
        <div>{this.state.a}</div>
        <A />
      </div>
    );
  }

Whenever I click the button, component A is rerendered (I can see "hello" in the console) I thought React was avoiding many useless rerenderings.每当我单击按钮时,组件 A 都会重新渲染(我可以在控制台中看到“hello”)我认为 React 避免了许多无用的重新渲染。

Your parent component is re-rendering because its state changes.您的父组件正在重新渲染,因为它的状态发生了变化。

When a component re-renders, all its children are re-rendered.当一个组件重新渲染时,它的所有子组件都会重新渲染。 This means that the render function runs, and the result is added to the virtual DOM.这意味着渲染函数会运行,并将结果添加到虚拟 DOM 中。

This result is then compared with the existing DOM.然后将此结果与现有 DOM 进行比较。 It doesn't mean that that actual DOM changes for the child components, just that they are re-evaluated because the DOM might need to change.这并不意味着子组件的实际 DOM 发生了变化,只是因为 DOM可能需要更改而重新评估它们。

If it turns out that the child element does need to change, then that element in the actual DOM is re-rendered.如果结果证明子元素确实需要更改,则重新渲染实际 DOM 中的该元素。 If the child element doesn't need to change, that element in the DOM remains un-effected.如果子元素不需要更改,则 DOM 中的该元素保持不受影响。

This is generally fine and has minimal to no performance impacts for small components, so usually you don't need to worry about it.这通常很好,并且对小组件的性能影响很小甚至没有,因此通常您无需担心。

If you have deep component hierarchies or components with complex render functions that perform computationally expensive operations, consider using React.memo if you feel that the render cycle is causing a hit on performance.如果您有很深的组件层次结构或具有复杂渲染功能的组件,这些组件执行计算成本高的操作,如果您觉得渲染周期对性能造成影响,请考虑使用React.memo

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

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