redux(四)用redux-thunk和redux中間件發送異步action

cnpm i redux-thunk,然後在store文件中引入,同時解構出redux的applyMiddleware,將thunk傳入中間件,將中間件傳入store:

import {createStore, applyMiddleware} from 'redux';
import reducer from "./reducer";//引入當前目錄下合併後的rreducer

import thunk from 'redux-thunk';

let store = createStore(reducer, applyMiddleware(thunk));
export default store;

更改actionCreator:

import {INT_NUMBER, DEC_NUMBER, INPUT_NUMBER}  from "./const"

let createAction = {
	intNumber(){
		// return {  //action是一個對象  必須有type字段
		// 	type:INT_NUMBER
		// }
		return dispatch=>{
			let act = {
				type:INT_NUMBER
			}
			setTimeout(()=>{//兩秒鐘之後再發送action
				dispatch(act);
			}, 2000)
		}
	},
	decNumber(){
		return {  //action是一個對象  必須有type字段
			type:DEC_NUMBER
		}
	},
	inputNumber(val){
		return {
			type: INPUT_NUMBER,
			val
		}
	}
}

export default createAction;

此時,++就是異步的操作了,兩秒鐘之後數據number纔會+1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章