通过使用Usestate vs push对数组性能增加反应

发布于 2025-01-19 10:58:18 字数 296 浏览 2 评论 0原文

当我向数组添加元素并希望使用该数组渲染组件时,如果我没记错的话,我必须使用 useState 钩子和展开运算符:

setTestArray(array => [...array, data]);

当我想在普通 JavaScript 中添加元素时,我只是用推。 将元素推入数组不是更快吗? 是否有办法避免这个问题,例如推送一个元素,然后“告诉 React”您希望使用该数组的组件重新渲染? 是否有其他方法可以将元素添加到具有更好性能的数组/集合?

刚刚开始反应,所以也许我在这里忽略了一些东西:/

When I add elements to an array and want to lead to a render of components using that array, I have to use the useState hook and the spread operator, if I'm not mistaken:

setTestArray(array => [...array, data]);

When I want to add an element in normal JavaScript, I just use push.
Isn't it much faster to just push an element to an array?
Isn't there a way to avoid this problem and e.g. push an element and then "say to React" that you want the components using that array to rerender?
Are there any other ways to add elements to an array/set that have a better performance?

Just getting started with react, so maybe I have overlooked something here :/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

追星践月 2025-01-26 10:58:18

反应状态是不变的,因此,如果您想更改状态,则必须再次设置状态。我敢肯定,在引擎盖下,React做了一些能够巧妙地重新渲染事物的明智差异。

React states are immutable, so if you want to change state you have to set the state again. I'm sure under the hood, react does some smart diffing that is able to re-render things smartly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文