使用状态钩子时,useState() 中的 react 如何为功能组件检索正确的状态对象和函数?
How does useState() in react retrieve the correct state object and function for a functional component when using the state hook?
我目前正在研究我对 react 中 useState 钩子的理解。
我想知道的是;当 useState 被调用时,它如何能够正确检索状态对象和可用于修改它的函数,对于那个特定的功能组件(假设它已经在第一次被调用时创建。)
表达我的问题的另一种方式是 count 和 setCount 存在于何处? useState() 显然 return 一个不同的状态对象和修饰符函数,具体取决于调用哪个功能组件 useState ,那么它是如何工作的?
我的猜测是形成了一个闭包,这意味着这个功能组件有一个词法环境,它由创建闭包时范围内的任何局部变量组成,这就是 count 和 setCount 的原因在调用 useState 时可用。但我无法证实这一点,因为涉及反应,我可能会偏离。
export const MyFunctionalComponent = () => {
const [count, setCount] = useState(0);
return (
<h1>This is my component.</h1>
);
}
谁能帮我解决这个问题?
@edit:我很确定我对闭包的思考还很遥远,查看反应库源代码我找到了 useState 函数的实现。
export function useState<S>(initialState: (() => S) | S) {
const dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
我可能需要深入挖掘并解压才能得到答案。
我在 React 文档页面上找到了以下内容,其中至少给出了 useState 如何能够为功能组件取回本地状态的基本描述。
React keeps track of the currently rendering component. Thanks to the Rules of Hooks, we know that Hooks are only called from React
components (or custom Hooks — which are also only called from React
components).
There is an internal list of “memory cells” associated with each
component. They’re just JavaScript objects where we can put some data.
When you call a Hook like useState(), it reads the current cell (or
initializes it during the first render), and then moves the pointer to
the next one. This is how multiple useState() calls each get
independent local state.
我目前正在研究我对 react 中 useState 钩子的理解。
我想知道的是;当 useState 被调用时,它如何能够正确检索状态对象和可用于修改它的函数,对于那个特定的功能组件(假设它已经在第一次被调用时创建。)
表达我的问题的另一种方式是 count 和 setCount 存在于何处? useState() 显然 return 一个不同的状态对象和修饰符函数,具体取决于调用哪个功能组件 useState ,那么它是如何工作的?
我的猜测是形成了一个闭包,这意味着这个功能组件有一个词法环境,它由创建闭包时范围内的任何局部变量组成,这就是 count 和 setCount 的原因在调用 useState 时可用。但我无法证实这一点,因为涉及反应,我可能会偏离。
export const MyFunctionalComponent = () => {
const [count, setCount] = useState(0);
return (
<h1>This is my component.</h1>
);
}
谁能帮我解决这个问题?
@edit:我很确定我对闭包的思考还很遥远,查看反应库源代码我找到了 useState 函数的实现。
export function useState<S>(initialState: (() => S) | S) {
const dispatcher = resolveDispatcher();
return dispatcher.useState(initialState);
}
我可能需要深入挖掘并解压才能得到答案。
我在 React 文档页面上找到了以下内容,其中至少给出了 useState 如何能够为功能组件取回本地状态的基本描述。
React keeps track of the currently rendering component. Thanks to the Rules of Hooks, we know that Hooks are only called from React components (or custom Hooks — which are also only called from React components).
There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.