避免状态同步陷阱
This post is about a bad code pattern I see quite often. It’s about state management, particularly state synchronization. Often it is a source of bugs, glitches, and performance problems.
这篇文章是关于我经常看到的糟糕代码模式。它涉及状态管理,特别是状态同步。它通常是错误、故障和性能问题的来源。
Usually it is solvable by adjusting the state shape. More precisely, splitting the state into pieces and merging the pieces later in selectors, render functions, or custom hooks. An interesting fact is that one of those states is empty or undefined, but the UI renders desired items anyway. It might seem unintuitive, but bear with me.
通常可以通过调整状态形状来解决。更准确地说,将状态拆分成多个部分,然后在选择器、渲染函数或自定义钩子中合并这些部分。有趣的是,其中一个状态是空的或未定义的,但用户界面仍然渲染所需的项目。这可能看起来不直观,但请耐心听我说。
During the Redux era, we discussed state shape a lot. It was called state normalization. Nowadays, it is rarely touched, even though it is still important. To make my thoughts easier to understand, I sometimes use Redux terminology, like selectors and actions, throughout this article.
在Redux时代,我们讨论了状态形状很多。这被称为状态规范化。如今,这个话题很少被提及,尽管它仍然很重要。为了使我的想法更易于理解,我有时在本文中使用Redux术语,如选择器和动作。
I’ll present the problem using an example of an orders table. The example is quite long, but I believe it is useful. It is based on a real-world application. I simplify, but in principle, I saw it in a real codebase.
我将通过一个订单表的示例来展示这个问题。这个示例相当长,但我相信它是有用的。它基于一个真实的应用程序。我进行了简化,但原则上,我在一个真实的代码库中看到了它。
One last note before we start: I talk about React but the ideas are applicable to any modern FE framework (regardless if signal-based or not).
在我们开始之前最后一点说明:我谈论的是 React,但这些想法适用于任何现代前端框架(无论是否基于信号)。
Example
示例
Let’s illustrate state synchronization through an evolving example, starting simply and becoming increasingly complex over several hypothetical years.
让我们通过一个不断演变的例子来说明状态同步,从简单开始,随着几个假设年份的推移变得越来越复杂。
2025: List of Orders
2025:订单列表
Date | # | Customer | Amount |
---|---|---|---|
1/3/2025 | 101 | Ondrej | 100 |
2/3/2025 | 102 | Jenny | 200 |
3/3/2025 | 103 | Hans | 300 |
日期 | # | 客户 | 金额 |
---|---|---|---|
2025年1月3日 | 101 | Ondrej | 100 |
2025年2月3日 | 102 | Jenny | 200 |
2025年3月3日 | 103 | Hans | 300 |
function OrdersLi...