一、安装使用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;
}
运行结果: