javascript - How this ReactJS syntax works?
问题描述
I see the following kinda code for state management in the latest Hook Based component syntax in ReactJS.
const [input, setInput] = React.useState("");
What is this syntax called? And how does React.useState()
creates and stores values in input
and setInput()
in local context?
解决方案
该React.useState()
方法返回一个array
带有两个值的值:第一个值是状态本身(在您的情况下是一个空字符串)。第二个值是改变状态的方法。我们使用左侧方括号的原因是为了以简洁的方式将它们设置为有意义的名称。JavaScript 允许我们以这种方式从数组中获取值。或者,您可以编写:const myArr = React.useState("")
然后const input = myArr[0]
andconst setInput = myArr[0]
这种从数组中获取值的方法称为数组解构
推荐阅读
- ios - swift:如何在 switch case 语句中替换 if else
- r - 创建具有 m 个级别的 n 个元素的所有可能组合
- javafx - 为什么在 TextFormatter 中没有调用 toString?
- python - 与 pandas 的近似连接
- javascript - 为什么 JavaScript 函数文档在函数之外?
- python - ImportError:没有名为 Include 的模块
- php - 如何从php中的文本文件中提取特定文本?
- google-cloud-vision - 谷歌云视觉 api 快速入门错误打开文件
- javascript - 将变量或属性值传递给 JavaScript 对象中的方法会返回“未定义”
- javascript - 在浏览器中将 URL 重新加载到定义的路由器路由时出现 404