react redux无法异步请求的问题(redux中间键 redux-thunk)
概述
- redux 里面 action 是无法进行异步操作的
- 这时我们就需要用到 redux 中间键来增强 action,使其能够执行 异步
- redux -thunk 官方介绍(英文)
- redux -thunk 介绍 ------ 来自搜索文章
- 下载 redux-thunk
yarn add redux-thunk
- 引入 redux-thunk
//store/index.js
import { createStore,applyMiddleware } from 'redux'; //⬅⬅⬅⬅⬅⬅
import reducer from "./reducer"
import thunk from 'redux-thunk' //⬅⬅⬅⬅⬅⬅
const store = createStore(reducer,applyMiddleware(thunk)); //⬅⬅⬅⬅⬅⬅
export default store
- 发送异步请求
之前的代码:
addNewTodo(title){ //actionCreators
let action = {
type:ADD_NEW_TODO,
title
}
//需要将action派发给reducer进行处理
return action
},
现在的代码:(因为 计时器也是异步的,所以这里使用 计时器来代替异步请求)
//store/actionCreators(action 创建的js 文件)
addNewTodo(title){
return dispatch=>{
setTimeout(() => {
dispatch({
type:ADD_NEW_TODO,
title
})
}, 1000);
}
}
效果展示:
版权声明:本文为qq_44163269原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。