redux-thunk配置
下载:npm install --save redux-thunk / yarn add redux-thunk
使用:
在 store文件夹下 index.js 中引入 applyMiddleware(redux中间件)
import { createStore , applyMiddleware , compose } from ‘redux’
import thunk from ‘redux-thunk’
如果没有使用redux-dev-tools :
const store = createStore(reducers,applyMiddleware (thunk))
export default store
如果使用了redux-dev-tools:
const myCompose = window .__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window .__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const store = createStore(reducers,myCompose(applyMiddleware (thunk)))
export default store
进行以上操作之后即可在action中发起异步请求(compose )为增强函数用于配置redux-dev-tools
redux-saga 配置:
下载: npm install --save redux-sage / yarn add redux-saga
使用:
在store文件夹下创建sagas.js
在store中index.js中引入 applyMiddleware (redux中间件)
import { createStore , applyMiddleware } from ‘redux’
import createSagaMiddleware from ‘redux-saga’
import mySagas from ‘./sagas’
const sagaMiddle = createSagaMiddleware()
如果没有使用redux-dev-tools :
const store = createStore(reducers,applyMiddleware (sagaMiddle))
sagaMiddle.run(mySagas)
export default store
如果使用了redux-dev-tools:
const myCompose = window .__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window .__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
const store = createStore(reducers,myCompose(applyMiddleware (sagaMiddle)))
sagaMiddle.run(mySagas)
export default store
在sagas.js中需使用ES6中的 Generator函数
Generator函数是ES6提供的一种异步编程解决方案,形式上也是一个普通函数,但有几个显著的特征:
– function关键字与函数名之间有一个星号 “*” (推荐紧挨着function关键字)
– 函数体内使用 yield 表达式,定义不同的内部状态 (可以有多个yield)
– 直接调用 Generator函数并不会执行,也不会返回运行结果,而是返回一个遍历器对象(Iterator Object)
– 依次调用遍历器对象的next方法,遍历 Generator函数内部的每一个状态
以上内容是我在学习redux时自己所记录下来的redux-thunk与redux-saga配置方法,如有遗漏欢迎指正