npm i -S redux-thunk
在 index.js
中,创建 Store 时开启中间件
import { createStore, applyMiddleware } from ‘redux’;
import { thunk } from ‘redux-thunk’;
const store = createStore(aReducer, applyMiddleware(thunk));
在 Reducer 中,创建一个同步方法,返回一个 Action
export function asynFunction() {
return (dispatch) => {
setTimeout(() => {
// 异步执行
// aFunction 是另一个 Action Creator
dispatch(aFunction());
}, 2000)
}
}
Shared-Bookmarks: category.redux.js 中的应用
export function fetchCategories(address) {
return ((dispatch) => {
dispatch(startFetchingBookmarks());
fetch(addProtocolIfNeeded(address))
.then((response) => {
return response.json();
})
.then((json) => {
dispatch(updateBookmarks(json));
})
.catch((e) => {
dispatch(failFetchingBookmarks());
});
});
}