Redux学习之旅七:Axios结合Redux异步获取数据

一、安装使用Axios

因为是新建的项目,所以需要再安装一下Axios:

npm install --save axios

在TodoList.js中引入:

import axios from 'axios';

 这里我们仍然使用制作react的小姐姐菜单时在easy-mock网站上模拟的数据接口。

在package.json文件中配置proxy实现跨域访问easy-mock网站:

{
  "name": "demo01",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    ...
  },
  "proxy": "https://www.easy-mock.com",
  "scripts": {
    ...
  },
  "eslintConfig": {
    ...
  },
  "browserslist": {
    ...
  }
}

在TodoList组件中编写生命周期函数componentDidMount获取远程接口数据:

componentDidMount() {
axios.get('/mock/5fa9f41e234c9b0d8babebae/ReactDemo01/xiaojiejie')
    .then((res) => {
        console.log(res.data.data);
    })
    .catch((error) => {
        console.log('axios获取数据失败' + error)
    })
}

运行项目,在浏览器中按F12查看控制台,数据成功被获取。

二、获取数据后与Redux结合

将获取的数据放到Redux的store中。首先在store/actionCreaters.js文件中编写一个新的函数:

export const getListAction = (data)=>({
    type:GET_LIST,
    data
})

在store/actionTypes.js文件中新建常量GET_LIST:

export const GET_LIST = 'getList'

将常量引入到actionCreaters.js文件中:

import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM,GET_LIST} from './actionTypes';

回到TodoList.js文件,在其中引入getListAction函数:

import { changeInputAction, addItemAction, deleteItemAction, getListAction } from './store/actionCreaters';

编写Axios回调内容,将数据通过dispatch传递给store:

componentDidMount() {
axios.get('/mock/5fa9f41e234c9b0d8babebae/ReactDemo01/xiaojiejie')
    .then((res) => {
        console.log(res.data.data);
        const action = getListAction(res.data.data);
        store.dispatch(action);
    })
    .catch((error) => {
        console.log('axios获取数据失败' + error)
    })
}

 编写reducer处理业务逻辑,进入store/reducer.js文件,增加判断:

if(action.type === GET_LIST){
    let newState = JSON.parse(JSON.stringify(state));
    newState.list = action.data;
    return newState;
}

运行结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值