前邊我們提到了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
相關的東西就介紹的差不多了,接下來我將帶來其他方面的前端知識,拜拜了~~~~