redux中间件

395 阅读1分钟

redux-thunk中间件

安装

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

使用

  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-saga

使用

  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)
  }