<center>使用Redux-thunk中间件实现ajax数据请求</center>

1.先安装redux-thunk依赖
npm install redux-thunk
yarn add redux-thunk
redux-thunk的GitHub网址 : https://github.com/reduxjs/redux-thunk
2.接下来我们要引入配置redux-thunk这个中间件参考上面GitHub的网址上的文档
3.打开store文件夹下的index文件引入redux-thunk和配置redux开发者工具
import { createStore , applyMiddleware , compose } from "redux";
import reducer from "./reducer";
import thunk from 'redux-thunk';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(
    applyMiddleware(thunk)
  );
const  store = createStore(reducer,enhancer);
export default store;
4.配置好后我们把组件里的异步代码移除,把异步代码移除到action中去
5.接下来我们打开actionCreators.js,当我们引用了Redux-thunk后action可以是一个函数
之前的action都是返回一个对象,现在可以用Redux-thunk返回一个函数
代码如下:
export const getTodoList = () => {
    return () => {
        axios.get('http://yapi.demo.qunar.com/mock/38353/app')
        .then((res) =>{
            const data = res.data;
            })
        .catch(() =>{alert('err')})
    }
}
6.此时我们发现getTodoList这个函数该怎么调用呢
7.接下来我们就要返回到TodoList这个组件中去调用,首先引入这个方法
import { getInputChangeAction , getAddItemAction , getDeletItemAction ,getTodoList} from './store/actionCreators.js';
8.然后我们在componentDidMount这个生命周期函数中引用getTodoList这个函数 代码如下 :

    componentDidMount() {
        const action = getTodoList();
        store.dispatch(action);
    }
9.接下来我们返会到actionCreators.js中编写异步代码记得引入axios的包
import axios from 'axios';
10.那store中的List数据应该怎么改变呢,此时我们又要发送action啦代码如下:
const action = initListAction(data)
11.我们发现actionCreators并没有store的dispatch方法,当调用getTodoList时会生成一个内容似的函数时,这个函数能接收到stored的dispatch方法,我们直接调用dispatch法方就可以了 代码如下
export const getTodoList = () => {
    return (dispatch) => {
        axios.get('http://yapi.demo.qunar.com/mock/38353/app')
        .then((res) =>{
            const data = res.data;
            const action = initListAction(data)
            dispatch(action);
            })
        .catch(() =>{alert('err')})
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值