【问题标题】:Why React useState return const array为什么 React useState 返回 const 数组
【发布时间】:2019-08-08 10:36:16
【问题描述】:

我目前正在学习 React 和 React hook。一个使用useState的经典例子如下:

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

我的问题是为什么返回的数组是 const?我认为至少 count 的值会随着时间而改变。

【问题讨论】:

标签: javascript reactjs react-hooks


【解决方案1】:

useState 返回的值不是 const 数组,而只是用户决定声明为const 的数组。将上述视为

const stateValue = useState(0);
const count = stateValue[0];
const setCount = stateValue[1];

简而言之,语法const [count, setCount] = useState(0);Array destructuring syntax

不是它被声明为const,因为您没有将countsetCount 重新分配给代码中的其他内容,而只是使用setCount 方法来更新状态计数。


React 作者决定返回一个包含 state valuestate setter 的数组,以便您可以随意命名,而不是在解构时使用预先确定的名称。

【讨论】:

  • “这样您就可以随意命名它,而不是在解构时使用预先确定的名称”这就是我一直在寻找的答案!
  • 如果 useState 将返回一个对象,那么名称将是固定的,这意味着您不能在同一组件中多次出现 useState。
猜你喜欢
  • 2020-03-10
  • 2020-05-22
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 2021-01-14
  • 2023-02-11
相关资源
最近更新 更多