redux-order
Redux order is a middleware to deal with Redux, which simplifies the asynchronous flow control processing of redux.
install
npm install redux-order
Introducing Redux order
import {createStore, applyMiddleware, compose} from 'redux';
import reduxOrder from 'redux-order';
import reducers from './reduces';
const enhancer = compose(
//Introduction of Middleware
applyMiddleware(reduxOrder())
);
const store = createStore(
reducers,
enhancer
);
export default store;
Asynchronous processing in reduce
// action
const LOGIN = 'auth/LOGIN';
const LOGIN_SUCCESS = 'auth/LOGIN_SUCCESS';
const LOGIN_FAIL = 'auth/LOGIN_FAIL';
const initialState = {};
// reducer
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case LOGIN:
console.log(action);
return {
...state,
requesting: true,
requested: false,
};
case LOGIN_SUCCESS:
console.log(action);
return {
...state,
requesting: false,
requested: true,
auth: action.res
};
case LOGIN_FAIL:
console.log(action);
return {
...state,
requesting: false,
requested: true,
loginError: action.err
};
default:
return state;
}
}
//Trigger action
export function login(user, pass) {
return {
types: [LOGIN, LOGIN_SUCCESS, LOGIN_FAIL],
promise: axios.post('/api/login', {user, pass}),
data: 'message',
list: [1, 2, 3, 4]
};
}
Asynchronous action
- In the example above, we created
asynchronous
Redux request for. This is defined in the exampleLOGIN
、LOGIN_SUCCESS
、LOGIN_FAIL
The three actions represent request sending, request success and request failure in turn. When issuing an asynchronouspromise
After the request, theLOGIN
If the request is successful, enterLOGIN_SUCCESS
Otherwise, they will enterLOGIN_FAIL
。 - Asynchronous actions need to be defined
types
, types is an array, and at least two actions (request and result) are required,promise
The parameter is an asynchronous request, which must be a promise object. - The result of the request is obtained in the action object in the reducer. If it is successful, the return result is
action.req
What failed wasaction.err
。 - When you issue an action, you can also carry a payload. You can customize the parameters you need to carry, and you can access the parameters carried by action in reducer.
Synchronous action
export function logout() {
return {
type: LOGOUT
};
}
The above is to trigger a synchronous action,type
Parameters define the actions to be triggered, and can also carry payload. be careful ⚠️ The asynchronous action parameter istypes
, while synchronous istype
。