Review the three basic principles of Redux design and use
- Single source of truth, meaning the state in the store is unique
- State is read-only. Redux does not expose an interface to directly modify state; changes must be triggered via actions (i.e., only the store can change its own state)
- Reducers must be pure functions
The Original Intent of Redux Design
Let's first explain why reducers must be pure functions from the design perspective of Redux.
Redux's design references the Flux pattern, and the author intended to achieve time travel, save the historical state of the application, and make the application state predictable. Therefore, the entire Redux follows the functional programming paradigm, and it is natural to require reducers to be pure functions. Using pure functions ensures that the same input yields the same output, guaranteeing predictability of state.
Redux Source Code
So what exactly does a reducer do? In Redux's source code, it is expressed in just one line:
currentState = currentReducer(currentState, action)
This line simply and directly explains at the code level why currentReducer must be a pure function. currentReducer is our reducer (interested readers can check the source code to see why it's called "current"). The reducer processes the state and action passed by the store and must return a new state. After the store receives this new state, it updates its own state.
The reducer is used to compute state, so its return value must be state, i.e., the entire application state, not something like a promise.
If you want to add asynchronous operations in a reducer, and you simply want to execute an asynchronous operation without waiting for its return, what is the point of executing it in the reducer? If you want to reflect the result of an asynchronous operation in the state, first the entire application state becomes unpredictable, violating Redux's design principles. Second, currentState would then be a promise or something else, rather than the desired application state (state), which is fundamentally unworkable.
Actually, this question might be better phrased as why Redux cannot have side effects in reducers.
暂无评论。