首页 > 解决方案 > 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?

标签: javascript

解决方案


React.useState()方法返回一个array带有两个值的值:第一个值是状态本身(在您的情况下是一个空字符串)。第二个值是改变状态的方法。我们使用左侧方括号的原因是为了以简洁的方式将它们设置为有意义的名称。JavaScript 允许我们以这种方式从数组中获取值。或者,您可以编写:const myArr = React.useState("")然后const input = myArr[0]andconst setInput = myArr[0] 这种从数组中获取值的方法称为数组解构


推荐阅读