Redux --- 簡單實現一個todoList (4) --- redux-thunk中介軟體
阿新 • • 發佈:2021-01-13
比如在Dispatch一個Action之後,到達reducer之前,進行一些額外的操作,就需要用到middleware(中介軟體)。 在實際工作中你可以使用中介軟體來進行日誌記錄、建立崩潰報告,呼叫非同步介面或者路由。
目的
有了react-thunk後,我們可以把 TodoList.js 中的 componentDidMount 業務邏輯放到這裡來編寫。也就是把向後臺請求資料的程式碼放到actionCreators.js檔案裡。這樣所有的業務邏輯都在redux中,方便集中管理。
1
安裝
yarn add redux-thunk -- save
引入,使用
import {createStore ,applyMiddleware} from 'redux';
import thunk from 'react-thunk';
const store = createStore(reducer,
applyMiddleware(thunk)
);
為了能夠用redux-dev-tool工具來除錯我們的程式碼,程式碼需要做一些改動,新增一個增強件compose,以及幾行固定程式碼,如下為index.js的完整程式碼
import { createStore , applyMiddleware ,compose } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const enhancer = composeEnhancers(applyMiddleware(thunk))
const store = createStore ( reducer, enhancer)
export default store
2
react-thunk的好處在於,以前的action是一個物件,現在的action可以是一個函數了。
以前的action是一個物件
onDeleteItem = (selectId) => {
const action = onDeleteItemAction(selectId); //呼叫的是物件
store.dispatch(action)
}
export const onDeleteItemAction = (selectId) => ({ //物件:{type:'',value:''}
type:DELETE_ITEM,
value:selectId
})
現在的action可以是函式,函式同樣寫入actionCreator.js
componentDidMount(){
const action = onGetInitList(); //這裡的action為函式
store.dispatch(action);
}
把有關的業務邏輯放在onGetInitList 函式中,並且呼叫onGetInitListType 物件
export const onGetInitList = () =>{
return (dispatch) => {
axios.get("https://5f48b1de57a10f001600ddf3.mockapi.io/api/todoList").then(res =>{
console.log(res);
const action = onGetInitListType(res.data); //這裡的action為物件
dispatch(action);
})
}
}
export const onGetInitListType = (data) => ({
type:GET_INITLIST,
data
})