单一事实来源是指每条数据恰好存储在一个地方,所有需要它的地方都从那里读取——而不是保留多个可能不同步的副本。
为什么这很重要:防止重复和发散的状态
jsx
() {
[user, setUser] = ({ : });
[displayName, setDisplayName] = ();
() {
({ ...user, : newName });
}
}
当同一个事实存在于两个状态中时,每次更新都必须同时改变两个地方——但不可避免地会有一个被遗漏,导致 UI 显示不一致值的bug。
// ✅ user.name is the single source; displayName is DERIVED, not stored
function Profile() {
const [user, setUser] = useState({ name: "Ann" });
const displayName = user.name.toUpperCase(); // computed on render — always in sync
function rename(newName) {
setUser({ ...user, name: newName }); // one update, everything stays consistent
}
}
将规范值存储一次;从它动态计算任何可推导的内容。没有什么需要保持同步。
✓ Don't copy props into state (the prop is the source)
✓ Don't store derived values (compute them: totals, filtered lists, formatted text)
✓ Global stores (Redux/Pinia): one store is the source for shared data
✓ Server data: cache it once (React Query) rather than copying into many components
✓ URL as source: filters/page in the URL, read from there
单一事实来源是可靠状态管理的基础原则——它消除了由重复数据偏离而引起的整个类别的bug。
这就是为什么你应该推导值而不是存储它们,为什么你应该避免将props复制到state中,以及为什么全局存储要集中共享数据。
当数据有唯一的权威来源,且一切都从它读取时,你的 UI 从构造上就保持一致。