在 React 中 State Hooks ,可以编写以下行来设置一个名为 count
的状态变量,然后使用 setCount
函数设置值,如下所示:
const [count, setCount] = useState(0);
这相当于写作:
this.state = { count: 0 };
我的问题是,useState()
函数如何从 ES6 Destructuring Assignment 语句中获取状态变量的名称——在本例中为 count
?
解构 不是发生在函数返回值之后吗?或者是否可以在函数被调用时动态获取正在被破坏的值?
更新
请注意,我知道我可以解构为我想要的任何名称,但是 useState()
如何知道什么变量应该进入 state,以便以后使用。
例如,如果我设置了两个状态变量,如果 useState()
函数不知道变量名称,它如何区分这两个值?
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
最佳答案
当你使用功能组件和 useState 时
const [myCountVariable, setCount] = useState(0);
您只能使用 myCountVariable 变量访问您的数据。 this.state 没有被使用。
如果我理解正确,您不理解的是它如何知道写入“this.state.myCountVariable”——它不知道。状态不存储实际的变量名。
就像我上面的帖子所说的那样,useState 假设每次组件调用它时,它都会以相同的顺序调用它,因此它会根据索引返回“变量持有者”。
在 React 文档中,您可以看到他们在 React Hook 规则中引用了这个:
Only Call Hooks at the Top Level Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)
基本上,
const [count, setCount] = useState(0);
更准确地表示为
componentStateContainer[currentStateIndex] = myStateVariable; //React doesn't know how you named your local variable
currentStateIndex++;
return [myStateVariable, setStateMethod]
(当函数组件被重新创建时,currentStateIndex会重置为0)
关于javascript - React State Hook如何从ES6 Destructuring Assignment中获取状态变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55649426/