之前的列表数据在reducer中写死了。
这篇文章实现从后端接口获取数据,如何可以放到Redux的store中。
1
用 mockAPI 模拟出数据,复制地址
https://5f48b1de57a10f001600ddf3.mockapi.io/api/todoList
2
1.在组件的生命周期中获取到以上数据 – 2. 通过action吧数据发送到reducer – 3. 在reducer中进行列表数据的初始化
componentDidMount(){
axios.get("https://5f48b1de57a10f001600ddf3.mockapi.io/api/todoList").then(res =>{ //--- 1
console.log(res); //结果见图1
const action = onGetInitList(res.data); // ---2 其中onGetInitList为上一篇文章分离出来的actionCreator.js中action具体函数
store.dispatch(action);
})
}
if(action.type === GET_INITLIST){
let newState = JSON.parse(JSON.stringify(state));
newState.list = action.data; // ---3
return newState;
}
图一
打印出来的res,模拟的列表数据在返回的res的data属性中
所以action要发送的是res.data,而不是res
3
打开看一下,效果完成,功能ok
藏之介白石❀