const [count,setCount] = useState(0)
这是useState的正常用法,我们可看到它返回的是一个数组。
为什么是数组而不是对象呢?
在回答这个问题前我们先要明白ES6的解构赋值:
这是数组的结构赋值:
const arr = [1,2,3];
const [one,tow,three] = arr;
console.log(one);//1
console.log(tow);//2
console.log(three);//3
我们再来看一下对象的解构赋值:
const user = {
id:1,
name:'李华'
};
const {id,name} = user;
console.log(id); // 1
console.log(name);// 李华
通过这两个对比,我们可以看出来,在数组中,我们可以对数组的元素进行命名,在对象中,我们必须要同名。
所以useState返回数组是为了降低使用的复杂度,让useState使用起来更加的灵活。