当前位置: 代码迷 >> 综合 >> redux(四)用redux-thunk和redux中间件发送异步action
  详细解决方案

redux(四)用redux-thunk和redux中间件发送异步action

热度:35   发布时间:2023-12-14 10:05:34.0

cnpm i redux-thunk,然后在store文件中引入,同时解构出redux的applyMiddleware,将thunk传入中间件,将中间件传入store:

import {createStore, applyMiddleware} from 'redux';
import reducer from "./reducer";//引入当前目录下合并后的rreducerimport 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(()=>{//两秒钟之后再发送actiondispatch(act);}, 2000)}},decNumber(){return {  //action是一个对象  必须有type字段type:DEC_NUMBER}},inputNumber(val){return {type: INPUT_NUMBER,val}}
}export default createAction;

此时,++就是异步的操作了,两秒钟之后数据number才会+1

  相关解决方案