The purpose of this article is to get a quick start on redux by discussing the basic usage of redux through the example of buying fruit.
Example: Buying fruit
One day, programmer a big (pseudonym) want to buy fruit to eat, discover village surroundings unexpectedly do not have fruit shop, then plan oneself to open a fruit shop to earn a bit small money.
A big analysis of the fruit shop business model. It’s basically dealing with each customer’s needs, and then keeping a ledger to see the profit and loss on a daily basis. Abstracting as a program, redux is good at listening to customers and recording the results of each action. Having a plan in mind, She began to write:
First, customers’ purchasing behavior is simulated:
const action = {
type: 'BUY_APPLE'./ / to buy apples
payload: {
count: 2 / / buy 2 jins}}Copy the code
Then different customers might want different weights, so he wrote the following method:
* @param {number} num */
function buyApple(num) {
return {
type: 'BUY_APPLE'.payload: {
count: num
}
}
}
Copy the code
Then there is the structure of the ledger, which records how many pounds are sold each day:
// Managed data state
// Account, today has sold apple: 0 kg; For simplicity's sake, just one example, there are actually lots of other fruits, so you can imagine
const state = { apple: 0 };
Copy the code
Okay, now that we have all the accounts for customer demand, who’s going to keep the books? So He hired a cashier to do the bookkeeping and told him to do it this way:
@param {object} state ledger * @param {object} action Customer demand */
function reducer(state, action) {
// Register the 'Buy Apple' event
// If someone buys apples, add the amount of apples the customer bought, update the account book
if (action.type === 'BUY_APPLE') {
return Object.assign({}, state, {
apple: state.apple + action.payload.count
});
}
// Unregistered events are not processed
// Buy things we don't have in our store, do not update the ledger, return as is
return state;
}
Copy the code
All right, we’re ready to officially monitor our customers’ purchasing needs and update our books:
const { createStore } = require('redux');
// Create a fruit store requires a cashier (listener) and an account (managed data)
const store = createStore(reducer, state);
Copy the code
Not only that, but Redux also offers a feature that allows you to do something extra for each customer you serve, so He wanted to see the ledger after each transaction:
// store.getState() to get the latest state
store.subscribe((a)= > console.log(JSON.stringify(store.getState())));
Copy the code
Well, the customers are coming for fruit:
// Trigger the user to buy fruit event
// The salesman starts selling
store.dispatch(buyApple(3)); // {"apple":3}
store.dispatch(buyApple(4)); // {"apple":7}
Copy the code
The stable operation of the store went on, and she felt very happy ~
Interpretation of the
The examples above cover several concepts of Redux: Action, Action Creator, State, and Store.
But before we do that, there are three important things about Redux:
- Only a single store object can hold the state of the entire application
- State is read-only and can only be changed by dispatch(Action)
- Reducer must be a pure function
action
An action is an abstraction of behavior information, an object type, that describes what happens. The object must have a type attribute. Redux does not restrict the rest of the object. However, Flux Standard Action specifications are recommended:
{
type: 'ACTION_TYPE',
payload, // The data carried by action
}
Copy the code
action creator
Action Creator, as the name suggests, is used to create actions, and action Creator simply returns the action.
function createAction(num) {
return {
type: 'ACTION_TYPE',
payload,
}
}
Copy the code
state
State is managed data, that is, the data we manipulate every time a listening event is triggered.
reducer
Reducer is the function used to control state changes. The action describes what happens, but does not know how the corresponding state should change. For different actions, corresponding state changes are described using reducer.
Reducer accepts two functions, the first state and the second action, and returns the new state after the calculation. Reducer must be a pure function and must return the same new state for the same input state and action.
nextState = reducer(prevState, action);
Copy the code
Because reducer is a pure function, the original prevState does not change and the new nextState is an updated snapshot.
store
A store is a large object that combines the above three elements:
{
createStore,
combineReducers,
bindActionCreators,
applyMiddleware,
compose,
__DO_NOT_USE__ActionTypes
}
Copy the code
It is responsible for:
- State of the hosted application
- Allowed to pass through
store.getState()
Method accesses managed state - Allowed to pass through
store.dispatch()
Method to trigger action to update state - Allowed to pass through
store.subscribe()
Register listener functions to listen for every action triggered - Allow logout to pass
store.subscribe()
Method to register a listener function
/ / register
const unsubscribe = store.subscribe((a)= > { /** do something */});
/ / logout
unsubscribe();
Copy the code
The illustration
Redux get started — Basic usage. Run Node./demo1/index.js directly from the console to see the effect
What is a Redux
Redux — Split Reducer