- 6-4 Redux 使用Redux-thunk中间件进行Ajax请求发送
引入thunk插件后,我们可以在
actionCreators内部编写逻辑
,处理请求结果。而不只是单纯的返回一个action对象。
thunk的原理,可以在actionCreators里通过返回一个函数,然后就可以在函数里编写某些异步操作了,待异步操作结束,最后通过传入的store.dispatch,发出action通知给Store要进行状态更新。
npm add redux-thunk
- gitHub中搜索
redux-devtools-extension
1.2目录处复制使用中间件 - 使用异步请求的中间件
store/index.js
使用 thunk
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;
- actionCreators.js
export const getTodoList = () => {
return () => {
axios.get("../../todoList.json")
.then(res => {
const data = res.data;
const action = getAjax(data);
store.dispatch(action);
})
}
}
- TodoList.js
const action = getTodoList ();
store.dispatch(action)
- 6-5 什么是Redux的中间件
- 用Redux Thunk 对Dispatch进行升级,这样就不仅可以使用对象,还能使用函数。基本没什么API,简单
- 6-6 Redux-saga 中间件的作用
- GitHub :
Redux-saga
非常大型项目更好用 npm add redux-saga
store/index.js
配置
import createSagaMiddleware from 'redux-saga';
import todoSagas from './saga';
// 创建 SagaMiddleware
const sagaMiddleware = createSagaMiddleware();
// 使用 SagaMiddleware
const enhancer = composeEnhancers(
applyMiddleware(thunk,sagaMiddleware)
);
// 创建sagaMiddleware 中间件
const store = createStore(reducer, enhancer);
// then run the saga
sagaMiddleware.run(todoSagas);
sagas.js
import { takeEvery , put} from 'redux-saga/effects';
import { GET_INIT_LIST } from './actionType'
import { initListAction } from './actionCreators';
import axios from 'axios';
// 一定要引入generrator 函数
function* todoSaga() {
// 捕捉action的类型 并 执行对应方法
yield takeEvery(GET_INIT_LIST, getInitListSaga);
}
// 执行的方法
function* getInitListSaga() {
try {
const res = yield axios.get('/todoList.json');
const action = initListAction(res.data);
// 传给store reducer进行处理
yield put(action);
}catch(e) {
console.log('list.json 404');
}
}