redux-thunk 異步中間件的簡單使用

前邊我們提到了redux的單獨使用和結合react-redux的使用方法,那麼作爲前端的工程師我們很重要的工作就是跟後端的交互,發送網絡請求後端接口,拿到數據渲染到頁面上從而展示給用戶。

我們都知道網絡請求是異步操作,所以我們在使用redux的時候action中需要用到中間件的處理,否則則會報出錯誤。

然而此類作用的中間件不只一個,今天只介紹redux-thunk,因爲它對於新朋友來說還是比較友好地,簡單易於使用,可快速上手(注:如果對redux的基礎不是很瞭解可以查看我前面的文檔)。接下來就來看redux-thunk怎麼來使用。

打開命令行工具:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章