gpt4 book ai didi

javascript - React 钩子(Hook)中的 `useState(null)[1]` 是什么?

转载 作者:行者123 更新时间:2023-12-02 06:46:24 26 4
gpt4 key购买 nike

我现在正在使用 React 钩子(Hook)。我看过useState(null)[1]但我忘记了我在哪里看到的。

我想知道与 useState(null) 有什么不同?

最佳答案

docs , 它说

Returns a stateful value, and a function to update it.



但他们的意思是

Returns an array where the first position is a stateful value, and the second position is a function to update it.



useState hook 返回一个数组,其中第一个位置(索引 0)是状态,第二个位置(索引 1)是该状态的 setter 。

所以当使用 useState(null)[1]您只会获得该状态的 setter 。

当你这样做
 const [state, setState] = useState(null)

你正在做的事情叫做 Destructuring Assignment

因为在大多数情况下,您希望同时拥有 statesetState , 解构使它使用起来比做起来容易得多。
const hook = useState(null)
const state = hook[0]
const setState = hook[1]

通过解构,你可以只用一条更干净的线来实现它

如果你只想要二传手,你可以这样做
const setState = useState(null)[1] // only getting the setter

请记住 两者都是一样的 .

I wonder what's different from useState(null)?


useState(null)返回一个数组 ( [state, setState])
useState(null)[1]正在访问返回的数组 ( setState)

关于javascript - React 钩子(Hook)中的 `useState(null)[1]` 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60075336/

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