redux-thunk和redux-saga

redux-thunkredux-saga都是redux的中间件,都是用来处理异步请求的。中间件是指在actionstore之间实现某种功能的函数
在这里插入图片描述

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函数,执行异步请求
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值