当前位置: 代码迷 >> 综合 >> redux-thunk使用
  详细解决方案

redux-thunk使用

热度:50   发布时间:2023-11-21 18:36:30.0

什么是thunk?

被 dispatch 的 function 会接收 dispatch 作为参数,并且可以异步调用它。这类的 function 就称为 thunk

安装redux-thunk

  npm install  redux-thunk --save

在react运用

import {counter} from './redux/index.redux'
import {createStore,applyMiddleware,compose}from 'redux'
import thunk from 'redux-thunk'const store=createStore(counter,compose(applyMiddleware(thunk)
));

**:compose 作用是从右到左来组合多个函数,在这里我们可以引入 devTools

一个异步函数获取数据:

export function getUserData(){return dispatch=>{axios.get('/data').then((res)=>{if(res.status===200){dispatch(userData(res.data))}})}
}export function userData(data){return{type:USER_DATA,payload:data}
}