useState通过闭包和内部状态数组按序存储,使函数组件能持久化状态;每次渲染时按调用顺序从数组中读取,setter通过闭包更新对应位置的值并触发重新渲染。

JavaScript中
useState
this.state
要理解
useState
useState(initialValue)
initialValue
这个setter函数很关键,它是一个闭包。它“记住”了它所关联的那个状态变量在框架内部存储的地址。当你调用这个setter函数时,它会更新内部存储的值,并且通知框架这个组件需要重新渲染。
当组件重新渲染时,整个函数组件会再次执行。这时,
useState
initialValue
useState
useState
可以想象框架内部有一个类似这样的结构:
// 这是一个极度简化的概念模型,实际框架会更复杂,性能优化也更多
let componentInternalState = []; // 存储所有组件实例的状态
let currentComponentCursor = 0; // 指向当前正在渲染的组件实例
let currentHookCursor = 0; // 指向当前组件中正在处理的hook
function renderComponent(ComponentFunction) {
// 模拟组件实例切换或新一轮渲染
// 实际框架中,这里会有组件ID或Fiber节点来精确管理
currentComponentCursor++;
currentHookCursor = 0; // 每次组件函数执行(渲染)时,hook指针重置
// 确保当前组件有自己的状态存储空间
if (!componentInternalState[currentComponentCursor]) {
componentInternalState[currentComponentCursor] = [];
}
const result = ComponentFunction(); // 执行组件函数
console.log(`--- Rendered Component ${currentComponentCursor} ---`);
console.log(result);
return result;
}
function useState(initialValue) {
// 获取当前hook在当前组件状态数组中的位置
const hookId = currentHookCursor;
// 如果是第一次渲染这个hook,则初始化其状态
if (componentInternalState[currentComponentCursor][hookId] === undefined) {
componentInternalState[currentComponentCursor][hookId] = initialValue;
}
// 获取当前状态值
let state = componentInternalState[currentComponentCursor][hookId];
// 定义setter函数,它是一个闭包,记住了hookId和currentComponentCursor
const setState = (newValue) => {
// 异步更新,模拟React的更新机制
setTimeout(() => {
// 如果newValue是函数,则调用它以获取新值(用于函数式更新)
const finalValue = typeof newValue === 'function' ? newValue(componentInternalState[currentComponentCursor][hookId]) : newValue;
componentInternalState[currentComponentCursor][hookId] = finalValue;
console.log(` -> State updated for hook ${hookId} in component ${currentComponentCursor}. New value: ${finalValue}`);
// 真实框架中,这里会触发一次调度,最终导致组件重新渲染
// 为了演示,我们不在这里自动调用renderComponent,而是让用户手动调用来观察效果。
}, 0);
};
currentHookCursor++; // 移动到下一个hook的位置
return [state, setState];
}
// 示例组件
function MyComponent() {
const [count, setCount] = useState(0);
const [name, setName] = useState('World');
console.log(` MyComponent State: Count=${count}, Name='${name}'`);
// 暴露setter,以便外部调用模拟更新
// 实际应用中,这些setter会绑定到事件处理器等
MyComponent.setCount = setCount;
MyComponent.setName = setName;
return `Current Count: ${count}, Current Name: ${name}`;
}
// 模拟第一次渲染
console.log("--- Initial Render ---");
renderComponent(MyComponent);
// 模拟外部触发状态更新
console.log("\n--- Simulating Updates (手动调用 renderComponent 才能看到效果) ---");
MyComponent.setCount(1);
MyComponent.setName('React');
MyComponent.setCount(prev => prev + 1); // 异步函数式更新
// 因为setState是异步的,并且上述简化模型没有自动触发重新渲染,
// 我们需要再次调用renderComponent来观察状态变化后的效果
// 在实际React中,setState会自动调度一次渲染
setTimeout(() => {
console.log("\n--- After first batch of updates (手动重新渲染) ---");
renderComponent(MyComponent); // 再次渲染,观察状态变化
}, 50);
setTimeout(() => {
MyComponent.setName('Universe');
console.log("\n--- After second update (手动重新渲染) ---");
renderComponent(MyComponent);
}, 100);
// 这段代码展示了核心思想:一个内部数组存储状态,一个指针追踪当前hook,
// setter通过闭包更新数组中的值。每次渲染,useState都从数组中按序取值。这段代码虽然简化,但清晰地展示了
useState
currentHookCursor
useState
currentHookCursor
useState
这确实是初学者常常疑惑,甚至一不小心就会踩坑的地方。核心原因在于,像React这样的框架,它内部维护着一个与组件实例生命周期绑定的“钩子列表”或者说“状态数组”。每次组件函数(也就是你的组件)被执行(渲染)时,
useState
想象一下,你有一个组件,里面写了:
const [count, setCount] = useState(0);
const [name, setName] = useState('Alice');当这个组件第一次渲染时,框架会把
0
'Alice'
useState(0)
useState('Alice')useState
count
'Alice'
所以,React官方文档里那句“不要在循环、条件或嵌套函数中调用 Hook”的规则,并非随口一说,而是其内部实现机制的必然要求。它确保了每次渲染时,每个
useState
useState
以上就是JS如何实现useState?状态的保存的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号