中間件就是在action中不直接去更新數據,而是要通過一定異步處理之后再去更新store里面的數據。
*這里以redux-thunk為例:
- 第一步安裝
cnpm install react-thunk --save
- 第二步: 使用createStore的第二個參數引用中間件
import {
createStore,
applyMiddleware
} from "redux"
// 使用中間件的步驟1
import logger from "redux-logger"
import thunk from "redux-thunk"
import {
deflate
} from "zlib";
const counterRdeux = (state = 0, action) => {
switch (action.type) {
case "add":
return state + 1;
case "minus":
return state - 1;
default:
return state
}
}
// 使用中間件的步驟2
const store = createStore(counterRdeux, applyMiddleware(logger, thunk))
export default store;
- 第三步:將對象改為函數形式調用中間件
const mapDispatchToProps = {
add: ()=> ( { type:"add"}),
minus: ()=> ({ type: "minus"}),
// return 一個函數就是異步操作
asyncAdd: () =>dispatch=> {
setTimeout(()=> {
dispatch({ type: "add"})
},1500)
}
}
- 以上就實現一個異步操作,在1.5s更新數據。