gpt4 book ai didi

reactjs - react是如何决定重新渲染组件的

转载 作者:行者123 更新时间:2023-12-03 22:53:23 24 4
gpt4 key购买 nike

我知道 React 有一个名为 shouldComponentUpdate 的生命周期方法, 默认情况下返回 true ,这就是组件决定更新的方式

但是当该组件的状态或 Prop 发生变化时,如何调用该生命周期方法。当我们收到新的 props 或 state 时会发生什么?当我们将一个组件连接到 redux state 和 mapStateToProps 时,我们是否在检查组件内部值的变化?如果没有,当我们在寻找 state 或 props 的变化时?

当 props 或 state 发生变化时,如何调用生命周期方法?。当 props 或 state 发生变化时,我们是否有一个监听器来调用这些方法?

最佳答案

您应该查看两者的生命周期,它们的执行方式以及调用每个方法的顺序。查看下面的 react 生命周期图像,您可以看到 componentWillMount 之间的区别和 componentDidMount和其他人如 componentDidUpdate , componentWillUpdate等等...

您还应该推理何时使用每种方法

要更新状态,请调用 this.setState()它告诉 react 某些东西发生了变化,它将重新渲染组件树。如果您使用 this.state.data = something react 不会触发 render()。现在要更新 Prop ,您需要了解 render() 的实际工作原理。这个答案已经从现有的 anwser 中总结出来:

Every time render() is called react will create a new virtual DOM where the root node is the component whose render function is called. The render() function is called when either the state or the props of a component or any of its children change. The render() function destroys all of the old virtual DOM nodes starting from the root and creates a brand new virtual DOM.

In order to make sure the re-rendering of components is smooth and efficient React uses the Diffing Algorithm to reduce the time it takes to create a new tree to a time complexity of O(n), usually time complexity for copying trees is > O(n^2). The way it accomplishes this is by using the "key" attribute on each of the elements in the DOM. React knows that instead of creating each element from scratch it can check the "key" attribute on each node in the DOM. This is why you get a warning if you don't set the "key" attribute of each element, React uses the keys to vastly increase its rendering speed.



react 生命周期



Redux 生命周期

enter image description here

关于reactjs - react是如何决定重新渲染组件的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56983445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com