一、简单使用axios模块实现
- 在actionType中添加异步数据需要的action类型
export const INIT_TODO_ITEM = 'init_todo_item'
- 在actionCreator中添加生成action的函数
export const getInitTodoItemAction = (list) => ({
type: INIT_TODO_ITEM,
list
})
- 在容器组件的ComponentDidMount中发送ajax请求,并生成和发送action
componentDidMount(){
axios.get('/getData').then(function(res){
const action = getInitTodoItemAction(res.data)
store.dispatch(action)
})
}
- 在reducer中添加处理action的方法
if(action.type === INIT_TODO_ITEM){
newState.list = action.list
return newState
}
二、使用redux-thunk中间件
redux-thunk是redux的中间件,它可以redux支持函数类型action的发送
- 配置中间件,在store的创建中配置
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;
- 添加一个返回函数的actionCreator,将异步请求逻辑放到这里
/**
发送get请求,并生成相应action,更新store的函数
@param url {string} 请求地址
@param func {function} 真正需要生成的action对应的actionCreator
@return {function}
*/
// dispatch为自动接收的store.dispatch函数
export const getHttpAction = (url, func) => (dispatch) => {
axios.get(url).then(function(res){
const action = func(res.data)
dispatch(action)
})
}
- 生成action,并发送action
componentDidMount(){
var action = getHttpAction('/getData', getInitTodoItemAction)
// 发送函数类型的action时,该action的函数体会自动执行
store.dispatch(action)
}
三、使用redux-saga中间件
redux-saga可以捕获action,然后执行一个函数,那么可以把异步请求代码放在这个函数中
- 配置中间件
import {createStore, applyMiddleware, compose} from 'redux';
import reducer from './reducer';
import createSagaMiddleware from 'redux-saga'
import TodoListSaga from './sagas'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const sagaMiddleware = createSagaMiddleware()
const enhancer = composeEnhancers(
applyMiddleware(sagaMiddleware)
);
const store = createStore(reducer, enhancer);
sagaMiddleware.run(TodoListSaga)
export default store;
- 将异步请求放在在sagas.js文件中
import {takeEvery, put} from 'redux-saga/effects'
import {initTodoList} from './actionCreator'
import {GET_INIT_ITEM} from './actionTypes'
import axios from 'axios'
function* func(){
try{
// 可以获取异步返回数据
const res = yield axios.get('/getData')
const action = initTodoList(res.data)
// 将action发送到reducer
yield put(action)
}catch(e){
console.log('网络请求失败')
}
}
function* mySaga(){
// 自动捕获GET_INIT_ITEM类型的action,并执行func
yield takeEvery(GET_INIT_ITEM, func)
}
export default mySaga
- 发送action
componentDidMount(){
const action = getInitTodoItemAction()
store.dispatch(action)
}