用redux-thunk中间件异步获取数据

上一个章节我们做了个一个简单的获取数据的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);
	};

最后效果一样一样的
image.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值