Redux data flow
First Dispatch triggers an action, then the Store automatically calls reducers and returns the new state. When the state changes, the Store calls the listener function and the view changes.
Redux does not support asynchronous actions
When we call an asynchronous operation within an action, we do the following:
Export function decreaseAsyncCount() {return () => {setTimeout(function () {store.dispatch(inscreaseCount()); }, 1000); }; }Copy the code
The result is the following error:
Our general solution is to use middleware, with Redux-Thunk and Redux-Saga being discussed the most.
Redux-thunk is different from redux-sage
These are the two most used and discussed plug-ins in the community.
redux-thunk
How to reference and associate redux-thunk I won’t go into it, there are a lot of information online. To get straight to the point, let’s look at the following code:
Export function decreaseAsyncCount() {return (dispatch) => {setTimeout(function () { dispatch(inscreaseCount()); }, 1000); }; }Copy the code
The above code uses redux-thunk, and when we return a function, Store calls the returned function for us and exposes the Dispatch for us to use. For the whole process of redux-thunk, after the asynchronous task is completed, dispatch is invoked, and store is invoked to reduce. , as shown below:
redux-saga
Here I also directly say the hour, first look at the following code:
import { takeEvery } from 'redux-saga'
import { call, put } from 'redux-saga/effects'
function* asyncGetData() {
yield* takeEvery('asyncGetData', asyncGetData)
}
function asyncGetData(action){
try {
// 执行函数
const data = yield call(Api.fetchUser, action.payload.url);
// 相当于dispatch
yield put({type: "FETCH_SUCCEEDED", data});
} catch (error) {
yield put({type: "FETCH_FAILED", error});
}
}
Copy the code
The above code uses the code of Redux-saga. When the action type of our dispatch is not reducer, the listening function takeEvery of Redux-saga will be monitored, and the put method will be implemented when the asynchronous task has the result, which is equivalent to dispatch. Trigger dispatch again. For the whole process of Redux-saga, it is to judge whether reducer has this action after action and reducer are executed, as shown below:
So in summary, redux-Thunk and Redux-Saga handle asynchronous tasks differently. In the case of Redux-Saga, a branch of Async Action is created to handle asynchronous tasks separately from redux actions
Saga has basically completely implemented asyC’s event listening mechanism, with much more code, and from my own experience redux-Thunk is much simpler and more relevant to Redux itself. Especially as the entire ecosystem moves toward functional programming, the higher-order functions of Redux-Thunk seem to fit this closed loop better.