我们可以在reactjs钩子中为useState()使用对象解构吗?

时间:2018-10-29 09:49:28

标签: javascript reactjs react-hooks

根据Hooks在Reactjs中的文档,

const [count, setCount] = useState(0);

它们使用数组解构。 我们可以用对象分解代替数组分解吗?

3 个答案:

答案 0 :(得分:3)

我完全同意@Patrick的回答。自从React团队实施以来,它遵守所有用例。实际上不需要将返回值放在对象中,因为它不需要通过键访问它,也不需要以后进行更新。此处的一个优势是解构,与数组相比,数组更容易处理对象。

我们已经看到const [count, setCount] = useState(0);,我们可以使用任何名称作为count和setCount。在对象中,我们需要这样做:

// grab the state value and setState func but rename them to count and setCount
   const { stateValue: count, setState: setCount } = useState(0);

在数组中

// grab in order and rename at the same time
   const [count, setCount] = useState(0);

答案 1 :(得分:2)

useState返回一个数组,因此,在这种情况下,您不必使用数组解构。

为了澄清,这并不意味着所有React钩子函数都需要返回一个数组。

如果您create your own hook,则可以让它返回任意内容,包括可以分解的对象。

答案 2 :(得分:0)

您不应该使用useState,但是...

如@SakhiMansoor所述,在setState情况下解构数组时,命名变量变得容易,因为它是通用钩子,您可以将其用于不同的数据,例如:

const [count, setCount] = useState(0);
const [age, setAge] = useState(0);
...

但是在创建自定义钩子时,我通常更喜欢对象。我们来看一个例子:

// If return an array
const [items, addItem, removeItem] = useItems();

// and only need `removeItem`, I write (I could easily forget one `,` here):
const [, , removeItem] = useItems();

// if I returned object, I would:
const { removeItem } = useItems();

在编写自定义的特定挂钩时,我通常不需要重命名键,因此在这种情况下对象工作得更好。