redux-thunk和redux-saga

redux-thunkredux-saga都是redux的中间件,都是用来处理异步请求的。中间件是指在actionstore之间实现某种功能的函数
redux-thunk和redux-saga_第1张图片

redux-thunk的用法

一般redux中action默认值返回对象,不能返回函数(会报错)。redux-thunk正好解决了这个问题,它使得action可以返回函数,一般我们就把异步请求写在函数里。
store/index.js

import { createStore, applyMiddleware, compose } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
const enhancer = composeEnhancers(
   applyMiddleware(thunk),
)
const store = createStore(
  reducer,
  enhancer
)
export default store

组件TodoList.js

import { getInitDataAction } from './store/actionCreator'
import store from './store'

componentDidMount() {
	const action = getInitDataAction() // getInitDataAction返回一个函数,返回时会执行这个函数
	store.dispatch(action)
}

actionCreator.js

import { INIT_TODO_LIST } from './actionTypes'
import axios from 'axios'

export getInitTodoListAction (data) => ({
	type: INIT_TODO_LIST, 
	data
})

export getInitDataAction = () => {
	return (dispatch) => {
		axios.get('/list.json').then(res => {
			const data = res.data
			const action = getIninTodoListAction(data)
			dispatch(action)
		})
	}
}

redux-saga的用法

redux-saga中间件会把所有异步请求放到一个文件,集中管理,原理是,组件dispatch某个action时,会被redux-saga捕获,再执行相应的函数,函数中执行异步请求。

store/index.js

import { createStore, applyMiddleware, compose } from 'redux'
import reducer from './reducer'
import createSagaMiddleware from 'redux-saga'
import mySaga from  './sagas.js'

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const sagaMiddleware = createSagaMiddleware()
const enhancer = composeEnhancers(
  applyMiddleware(sagaMiddleware)
)
const store = createStore(
  reducer,
  enhancer
)
sagaMiddleware.run(mySaga)

export default store

sagas.js

import { put, takeEvery } from 'redux-saga/effects'
import { GET_INIT_DATA } from './actionTypes'
import { getInitTodoListAction } from './actionCreator'
import axios from 'axios'

function* getInitList() {
  try {
    const res = yield axios.get('/list.json')
    const action = getInitTodoListAction(res.data)
    yield put(action)
  } catch(e) {
    console.log('list.json 连接网络失败')
  }
}

function* mySaga() {
  yield takeEvery(GET_INIT_TADA, getInitList) //当GET_INIT_TODO_LIST的action被dispatch时执行getInitList函数
}

export default mySaga

store/actionCreator.js

import { INIT_TODO_LIST, GET_INIT_DATA } from './actionTypes'
import axios from 'axios'

export getInitTodoListAction (data) => ({
	type: INIT_TODO_LIST, 
	data
})

export getInitDataAction () => ({
	type: GET_INIT_DATA
})

组件TodoList.js

import { getInitDataAction } from './store/actionTypes'
import store from './store'

componentDidMount() {
	const action = getInitDataAction() 
	store.dispatch(action) // redux-saga会捕获到action.type=GET_INIT_DATA的动作,再执行sagas.js中的getInitList函数,执行异步请求
}

你可能感兴趣的:(react,redux)