Skip to content

Bug: useState 不更新 UI

错误信息

                状态 appears 到更新但 UI doesn't 更改
              

快速摘要

你 mutated 状态 directly 相反的 calling setter 使用新 值, 所以 React didn't detect 更改 and didn't re-渲染.

为什么发生

  • Mutated 状态 directly: 状态.项.推送(newItem) 相反的 创建新 数组

  • Mutated 对象属性: 状态.用户.name = '新' 相反的 创建新 对象

  • 通过相同引用到 setState: setState(状态)

  • Used == 相反的 === in comparison 那个 controls 渲染

最小示例

✗ 错误代码
const [items, setItems] = useState([]);
items.push(newItem); // Direct mutation!
setItems(items); // Same reference, no re-render
✓ 修复代码
const [items, setItems] = useState([]);
setItems([...items, newItem]); // New array reference

React compares 新状态引用到 旧 one. Spreading 创建新 数组, 所以 React detects 更改 and re-渲染.

如何诊断

  • 检查如果你're 创建新 对象/数组 or mutating existing ones

  • Log 状态之前 and 之后到 see 如果引用更改

  • Use React DevTools 到 inspect 状态更新

如何修复

  • 创建新 数组: setItems([...项, newItem])

  • 创建新 对象: setUser({ ...用户, name: '新' })

  • Use updater 函数表单: setItems(prev => [...prev, newItem])

如何预防

  • 从不 mutate 状态 directly — 总是创建新 对象/数组

  • Use 不可变数据库 (Immer) for 复杂状态

  • 启用 ESLint 否-param-reassign 规则

相关资源

相关术语

相关课程

  • 状态

    学习不可变状态更新.

← 返回语言