redux中間件

redux-thunk中間件

安裝

命令:yarn add redux-thunk 或者npm install redux-thunkios

使用

  1. 在stroe中的index.js配置
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducer'
//配置redux-tools調試工具
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
//redux-thunl中間件
const enhancer = composeEnhancers(
  applyMiddleware(thunk),
)
const store = createStore(
  reducer,
  enhancer
)
export default store
複製代碼
  1. actionCreators.js文件中加入異步請求
//redux-thunk中間件異步請求
export const getTodoList = () =>{
//調用該方法時候會接收store的dispatch方法
  return (dispatch) =>{
    axios.get('https://easy-mock.com/mock/5d47d5aa08df77442c350799/api/getlist').then((res) => {
      console.log(res.data.data);
      const data = res.data.data.list
      const action = getinitList(data)
      dispatch(action)
    })
  }
}
複製代碼
  1. 組件中調用actionCreators.js內的異步方法
componentDidMount() {
    const action = getTodoList()
    store.dispatch(action)
  }
複製代碼

redux-saga中間件

安裝

命令:npm install --save redux-saga或者yarn add redux-saganpm

使用

  1. 在stroe中的index.js配置(添加中間件)
import { createStore, applyMiddleware } from 'redux'
import reducer from './reducer'
import createSagaMiddleware from 'redux-saga'
import todoSagas from './sagas'

const sagaMiddleware = createSagaMiddleware()
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
const enhancer = composeEnhancers(
  applyMiddleware(sagaMiddleware)
)
const store = createStore(
  reducer,
  enhancer
)
sagaMiddleware.run(todoSagas)
export default store
複製代碼
  1. 配置sagas.js文件,異步邏輯拆分至sagas.js
import { put, takeEvery } from 'redux-saga/effects'
import { GET_LIST } from './actionTypes'
import { getinitList } from './actionCreators'
import axios from 'axios'

function* getinitlist() {
  try {
    const res = yield axios.get('https://easy-mock.com/mock/5d47d5aa08df77442c350799/api/getlist')
    console.log(res.data.data);
    const action = getinitList(res.data.data)
    put(action)
  } catch (error) {
    console.log(error);

  }

}
//generator函數
function* mySaga() {
  //捕捉action類型,執行方法
  yield takeEvery(GET_LIST, getinitlist);
}

export default mySaga;
複製代碼
  1. 組件中配置dispatch
componentDidMount() {
    const action = getList()
    store.dispatch(action)
  }
複製代碼
相關文章
相關標籤/搜索