命令:yarn add redux-thunk 或者npm install redux-thunkios
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
複製代碼
//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)
})
}
}
複製代碼
componentDidMount() {
const action = getTodoList()
store.dispatch(action)
}
複製代碼
命令:npm install --save redux-saga或者yarn add redux-saganpm
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
複製代碼
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;
複製代碼
componentDidMount() {
const action = getList()
store.dispatch(action)
}
複製代碼