gpt4 book ai didi

reactjs - React Hooks - 为什么数组解构优于对象解构?

转载 作者:行者123 更新时间:2023-12-04 17:35:00 24 4
gpt4 key购买 nike

我刚刚开始编写一些自定义钩子(Hook)并弹出了一个问题,我应该将一组值作为数组还是作为对象返回?
useState 返回一对值的数组而不是具有两个属性的对象是否有特定原因?
我觉得我读过一些关于这个的东西,但不记得在哪里。
谢谢

最佳答案

扩展 @Vishwas comment ,这与命名有关。

这在 fine print of the useState docs 中简要提到.

When we declare a state variable with useState, it returns a pair — an array with two items. The first item is the current value, and the second is a function that lets us update it. Using [0] and [1] to access them is a bit confusing because they have a specific meaning. This is why we use array destructuring instead.


const [someValue, someUpdateFunction] = useState(0);
React 在后台处理数据 array[0]作为当前值,以及 array[1] 处的数据作为更新功能。只有职位很重要,而不是命名。当开发者实现 useState ,它们可以为这些位置的值提供有意义的名称。

关于reactjs - React Hooks - 为什么数组解构优于对象解构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57025886/

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