前边我们提到了redux
的单独使用和结合react-redux
的使用方法,那么作为前端的工程师我们很重要的工作就是跟后端的交互,发送网络请求后端接口,拿到数据渲染到页面上从而展示给用户。
我们都知道网络请求是异步操作,所以我们在使用redux
的时候action
中需要用到中间件的处理,否则则会报出错误。
然而此类作用的中间件不只一个,今天只介绍redux-thunk
,因为它对于新朋友来说还是比较友好地,简单易于使用,可快速上手(注:如果对redux
的基础不是很了解可以查看我前面的文档)。接下来就来看redux-thunk
怎么来使用。
打开命令行工具:
- 通过
yarn add redux-thunk
进行安装
在原有使用基础上找到store文件:
import { createStore, applyMiddleware } from "redux"; //导入applyMiddleware
import thunk from "redux-thunk"; // 导入thunk
import list from "../reducer/list"; // reducer
export default function configStore() {
const store = createStore(list, applyMiddleware(thunk)); // 加载中间件
return store;
}
这里写一个简单具有异步网络请求的action:
export default {
asyncHandle() { // 异步action
return dispatch => { // 返回的不再是对象而是回调函数
fetch(" http://jx.xuzhixiang.top/ap/api/productlist.php?uid=29044")
.then(res => res.json())
.then(data => {
dispatch({ // 通过传过来的dispatch进行给reducer的传感
type: "INITLIST",
data
});
});
};
}};
action的调用跟之前没有区别:
import React, { Component } from "react";
import { connect } from "react-redux";
import actionCreator from "../action/";
class DemoOne extends Component {
initList = () => {
this.props.asyncHandle();
};
render() {
console.log(this.props.list)
return (
<div> 123
<button onClick={this.initList}>发送请求</button>
</div>
);
}
}
export default connect(state => state, actionCreator)(DemoOne);
当点击按钮调用那个异步action的时候我们就拿到了数据:
到这就完成了redux-thunk
的基本使用,相信大家感觉也很容易吧!
那么到此呢三篇文章关于在react
中使用redux
相关的东西就介绍的差不多了,接下来我将带来其他方面的前端知识,拜拜了~~~~