react入門系列之使用redux-thunk中間件發(fā)起異步請求

redux-thunk

  • redux-thunk是redux中的一個中間件
  • 安裝命令 yarn add redux-thunk
  • 在store文件夾中的index.js中引入applyMiddleware,這樣我們才能使用中間件
  • 然后再引入redux-thunk
  • 并在createStore中使用applyMiddleware(thunk)

到底生命是redux中間件

  • 誰和誰之間
  • action和store之間
  • 其實中間件就是對dispath一個封裝
  • 如果傳遞的是一個函數(shù),會讓這個函數(shù)先執(zhí)行再傳遞給store
  • 如果是一個對象,就直接傳遞給store
  • 所以使用thunk中間件以后action可以是一個函數(shù)
/**
 * store就像一個圖書管理員,在接到組件(借書人)派發(fā)的 dispatch(借書人說的話) 時,
 * 他本身不知道書在什么位置,有沒有這本書,需要查詢 reducer (圖書列表)
 */
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import todoListReducer from './reducer' // 引入圖書列表

// 使用redux-devtools中間件和redux-thunk中間件

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose
const enhancer = composeEnhancers(
    applyMiddleware(thunk)
)
const store = createStore(
    todoListReducer,
    enhancer
) // 查詢圖書列表

export default store

使用redux-thunk

  • 在項目中使用引入使用redux-thunk之后
  • 在actionCreators中創(chuàng)建action不再只能創(chuàng)建對象action了,能夠創(chuàng)建函數(shù)形式的action
  • 因為action能是個函數(shù),所以我們可以把異步請求放在action中而不是放在生命周期函數(shù)里面
  • 項目大的時候邏輯復雜的時候,異步請求放在鉤子函數(shù)里是不好的
import { CHANGE_INPUT_VALUE, CHANGE_LIST_VALUE, DELETE_LIST_VALUE, INIT_DATA } from './actionTypes'
import mockData from '../mockjs/mock';
import axios from 'axios'

export const getInputChangeValue = (value) => ({
    type: CHANGE_INPUT_VALUE,
    value
})

export const getAddTodoListValue = (item) => ({
    type: CHANGE_LIST_VALUE,
    item
})

export const getDeletTodoListValue = (index) => ({
    type: DELETE_LIST_VALUE,
    index
})

export const initData = (data) => ({
    type: INIT_DATA,
    data
})
/**
 * 因為使用了redux-thunk所以在actionCreators中的箭頭函數(shù)可以返回一個函數(shù)
 */
export const getToduList = () => {
    return (dispatch) => { // 這個action返回的是這樣一個箭頭函數(shù),在使用的時候同樣頁需要通過dispatch派發(fā),箭頭函數(shù)中dispath其實就是在派發(fā)這個action的時候傳遞進來的
        axios.get('http://getTodoList', {dataType: 'json'}).then(res => {
            const action = initData(res.data.data)
            dispatch(action)
        })
    }
}

在組件中使用這個異步請求

  • 在componentDidMount函數(shù)中使用了
/**
 * 組件就是一個需要借書的人,通過 dispatch 傳達 action (書名)給圖書管理員(store)
 */

import React, { Component }from 'react';
import { message } from "antd";
import store from './store'; // 引入圖書管理員 store
import AppUi from './AppUi';
// import mockData from './mockjs/mock';
// import axios from 'axios'
// 引入action
import { getInputChangeValue, getAddTodoListValue, getDeletTodoListValue, getToduList } from './store/actionCreators'
// import { CHANGE_INPUT_VALUE, CHANGE_LIST_VALUE, DELETE_LIST_VALUE } from './store/actionTypes'
import "antd/dist/antd.css";
class App extends Component {
  constructor(props){
    super(props)
    this.state = store.getState()
    console.log(store.getState())
    this.handleInputChange = this.handleInputChange.bind(this);
    this.addTodoList = this.addTodoList.bind(this);
    this.handleStroeChange = this.handleStroeChange.bind(this);
    this.deletTodoList = this.deletTodoList.bind(this);
    store.subscribe(this.handleStroeChange) // 圖書管理員會隨時通知各個借書人,圖書館書籍的變化
  }
  componentDidMount (){
    // 引入了actionCreators中的getToduList方法,他返回的是一個函數(shù)action
    const action = getToduList()
    // 所以這里使用dispact去派發(fā)這個action
    store.dispatch(action)
    /*
    axios.get('http://getTodoList', {dataType: 'json'}).then(res => {
      console.log(res.data.data)
      this.init(res.data.data)
      console.log(this.state)
    })
    */
  }
  render() {
    return (
      <AppUi
      inputValue = {this.state.inputValue}
      handleInputChange = {this.handleInputChange}
      deletTodoList = {this.deletTodoList}
      addTodoList = {this.addTodoList}
      list = {this.state.list}
      />
    )
  }
  handleInputChange(e) {
    /*
    const action = {
      type: CHANGE_INPUT_VALUE, // 借什么書
      value: e.target.value
    }
    */
    const action = getInputChangeValue(e.target.value)
    store.dispatch(action); // 傳達給store
    console.log(e.target.value)
  }
  /*
  // 數(shù)據初始化
  init(data) {
    const action = initData(data)
    store.dispatch(action)
  }
  */
  // 添加
  addTodoList() {
    /*
    if (this.state.inputValue) {
      const action = {
        type: CHANGE_LIST_VALUE,
        item: this.state.inputValue
      }
      store.dispatch(action)
    } else {
      message.warning('請輸入內容');
    }
    */
   if (this.state.inputValue) {
      const action = getAddTodoListValue(this.state.inputValue)
      store.dispatch(action)
   } else {
    message.warning('請輸入內容');
   }
  }
  // 刪除
  deletTodoList(index) {
    /*
    const action = {
      type: DELETE_LIST_VALUE,
      value: index
    }
    */
   console.log(index)
    const action = getDeletTodoListValue(index)
    store.dispatch(action)
  }
  handleStroeChange() {
    this.setState(store.getState()) // 每當圖書館有變化的時候,圖書管理員(store)通過這個方式告訴借書人(組件)
  }
}

export default App;

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容