The main goal of action in Redux is to reduce state. The Reduce method will be called over an array of actions (that's why he called the reducer ) Example:
import reducer from './reducer'; const actions = [ {type: 'INIT'}, {type: 'SOME_ACTION', params: {...}}, {type: 'RECEIVE_DATA', data: [...]}, {type: 'SOME_ANOTHER_ACTION', params: {...}}, {type: 'RECEIVE_DATA', data: [...]}, ... ]; const finalState = actions.reduce(reducer, undefined);
Creators of an Action is a function that can create actions . It is not necessary for the action creator to create only one action.
In fact, if your reducer can receive functions instead of objects, your actions will be functions, and this will be the main goal, but you may lose some of the benefits of Redux functionality.
In this case, the gearbox will be implemented as follows:
function reducer(state, action) { return action(state); }
Reasons why you can create actions in the {type: 'ACTION_NAME'} format:
- Redux DevTools expects this format.
- You need to keep the sequence of actions.
- The gearbox performs state conversions for the worker.
- Everyone in the Redux ecosystem uses this format. This is a kind of agreement.
- Hot restart options (your saved functions will not restart).
- You need to send actions as on the server.
- Debugging Benefits - View a stack of actions with action names.
- Writing unit tests for the gearbox:
assert.equal(finalState, expectedState) . - A more declarative code — the name and parameters of the action — is “what to do” rather than “how to do” (but
addTodo('Ask question') also declarative).
Note on the relationship between action creators and state changes
Just compare the two entries:
At first:
function someActionCreator() { return { type: "ADD_TODO", text: "Ask question on stackoverflow" };
Secondly:
function someActionCreator() { return addTodo("Ask question on stackoverflow");
“In both cases, we see that the code is declarative and the creator of the action is separate from the state change. You can reuse addTodo or send two addTodo or use middleware or send compose(addTodo('One'), addTodo('Two')) . The main difference is that we created an object and a function and placed it in the code in which the state changes.