核心提示:问题描述异步的action中,我们有一个中间件的概念。什么是中间件,我们先不用管。但是我们要看到,我们上面的处理逻辑的不足之处。目前只有同步的dispatch。而没有异步的dispatch。为了解决这...
问题描述
异步的action中,我们有一个中间件的概念。
什么是中间件,我们先不用管。但是我们要看到,我们上面的处理逻辑的不足之处。
目前只有同步的dispatch。而没有异步的dispatch。
为了解决这个问题,redux有了中间件的概念。
在这些中间件中,redux-thunk是最常用,最实用的一个中间件,允许我们进行异步dispatch。
也就是我们可以dispatch一个function。
使用
import { createStore,applyMiddleware,combineReducers } from 'redux';
import thunkMiddleWare from 'redux-thunk'
const store = createStore(reducerss,applyMiddleware(
thunkMiddleWare
));
一个经典的示例就是,进行数据请求的三个状态。数据请求开始、数据请求成功、数据请求失败。
三种状态,对应三种视图。
//定义三个action
function RequestStart(data) {
return {
type: "START",
arr:data
}
}
function RequestSuc(data) {
return {
type: "SUC",
arr:data
}
}
function RequestFail() {
return {
type: "FAIL"
}
}
一般而言,一个异步的actionCreator可能是这样的。
var url = 'https://datainfo.duapp.com/shopdata/getclass.php';
function fetchAction(url) {
return dispatch => {
//开始的时候进行dispatch
dispatch(RequestStart([]));
fetch(url).then(res => {
console.log(res);
return res.json();
}).then(data=>{
console.log(data)
//成功的情况下的dispatch。
dispatch(RequestSuc(data))
})
}
}
这就是异步的dispatch。


