上一个章节我们做了个一个简单的获取数据的todolist,但是有些缺点
1:异步数据获取 全部放在componentDidMount里面,业务功能有耦合
2:不方便测试运营人员维护和调试
现在我们使用redux-thunk来做优化,提取出来放入一个action,好上代码
1:安装redux-thunk
cnpm install redux-thunk
2:在actionCreater.js中定义一个getTodoList,注意这里不是访问对象了,是返回一个函数,函数中再把获取数据的axios放在这里执行,一定要return才可以哦
//用redux-thunk 提取后台获取接口数据
export const getTodoList = (data)=>{
return (dispatch)=>{
axios.get("/api/list").then((res)=>{
let list =res.data.data;
console.log(list);
const action = getDataAction(list);
//store.dispatch(action);
//也可以直接dispath调用了 要传过来
dispatch(action);
}).catch(err=>{
console.log(err)
});
};
};
ps:dispatch可以再使用的时候,直接定义引入
3:修改TodoList.js,这里就不发送axios请求了,直接调用我们定义的action就可以了
componentDidMount(){
//let api = "http://localhost:3333/api/list";
// let api = "/api/list";
// axios.get(api).then((res)=>{
// console.log(res.data.data);
// let list =res.data.data;
// const action = getDataAction(list);
// store.dispatch(action);
// }).catch(err=>{
// console.log(err)
// });
//使用redux-thunk之后
const action =getTodoList()
store.dispatch(action);
};
最后效果一样一样的