Skip to main content

动机

¥Motivation

随着 JavaScript 单页应用的要求变得越来越复杂,我们的代码必须管理比以往更多的状态。此状态可以包括服务器响应和缓存的数据,以及尚未保存到服务器的本地创建的数据。UI 状态的复杂性也在增加,因为我们需要管理活动路由、选定的选项卡、加载控件、分页控件等。

¥As the requirements for JavaScript single-page applications have become increasingly complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally created data that has not yet been persisted to the server. UI state is also increasing in complexity, as we need to manage active routes, selected tabs, spinners, pagination controls, and so on.

管理这种不断变化的状态很困难。如果一个模型可以更新另一个模型,那么视图可以更新一个模型,模型更新另一个模型,这反过来可能会导致另一个视图更新。在某些时候,你不再了解应用中发生了什么,因为你失去了对其状态的时间、原因和方式的控制。当系统不透明且不确定时,很难重现错误或添加新功能。

¥Managing this ever-changing state is hard. If a model can update another model, then a view can update a model, which updates another model, and this, in turn, might cause another view to update. At some point, you no longer understand what happens in your app as you have lost control over the when, why, and how of its state. When a system is opaque and non-deterministic, it's hard to reproduce bugs or add new features.

好像这还不够糟糕,考虑一下前端产品开发中日益常见的新需求。作为开发者,我们需要处理乐观更新、服务器端渲染、在执行路由转换之前获取数据等等。我们发现自己正试图管理以前从未处理过的复杂性,我们不可避免地会问这样的问题:是时候放弃了吗? 答案是不。

¥As if this weren't bad enough, consider the new requirements becoming common in front-end product development. As developers, we are expected to handle optimistic updates, server-side rendering, fetching data before performing route transitions, and so on. We find ourselves trying to manage a complexity that we have never had to deal with before, and we inevitably ask the question: is it time to give up? The answer is no.

这种复杂性很难处理,因为我们混合了人类大脑很难推断的两个概念:突变和异步。我称它们为 曼妥思和可乐。两者分开时可以很好,但放在一起就会造成混乱。像 React 这样的库试图通过删除异步和直接 DOM 操作来解决视图层中的这个问题。但是,管理数据状态由你决定。这就是 Redux 的用武之地。

¥This complexity is difficult to handle as we're mixing two concepts that are very hard for the human mind to reason about: mutation and asynchronicity. I call them Mentos and Coke. Both can be great in separation, but together they create a mess. Libraries like React attempt to solve this problem in the view layer by removing both asynchrony and direct DOM manipulation. However, managing the state of your data is left up to you. This is where Redux enters.

遵循 通量CQRS事件溯源 的步骤,Redux 尝试通过对更新发生方式和时间施加某些限制来使状态突变可预测。这些限制都体现在 Redux 的 三个原则 中。

¥Following in the steps of Flux, CQRS, and Event Sourcing, Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.