P17:Redux进阶-Redux-saga的安装和配置
首先声明一下,文中讲的中间件不是React
的中间件,而是Redux
的中间件,这一点你要明白,否则工作中会出大问题的,你的React
知识架构也会出现偏差。其实Redux
的中间件不仅仅只有Redux-thunk
,还有一个比较出名的是Redux-saga
.当然这个中间件我们公司并没有使用,只是自己研究,所以可能讲解有不足的地方。目前国内的 IT 企业一般都在使用这两个中间件,使用其它的很少,所以很有必要学习一下。
redux-saga 的安装
你可以直接使用npm
来进行安装,当然用yarn
也是没有问题的,根据自己的喜好吧。我这里使用了npm
来进行安装。
npm install --save redux-saga
github 地址,方便你更好的学习。
引入并创建Redux-saga
安装好后,就可以使用了,直接在/src/store/index.js
里引入redux-saga
,并创建一个sagaMiddleware
,代码如下:
import createSagaMiddleware from 'redux-saga' //引入 saga const sagaMiddleware = createSagaMiddleware(); //创建 saga 中间件
创建好后,还是用 Redux 的增强函数进行传递。也就是把原来的Redux-thunk
替换成saga
中间件(注意去掉原来不用的redux-thunk
引入)。
import { createStore , applyMiddleware ,compose } from 'redux' // 引入 createStore 方法 import reducer from './reducer' //------关键代码----start----------- import createSagaMiddleware from 'redux-saga' const sagaMiddleware = createSagaMiddleware(); //------关键代码----end----------- const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose //------关键代码----start----------- const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware)) //------关键代码----end----------- const store = createStore( reducer, enhancer) // 创建数据存储仓库 export default store //暴露出去
这步完成后,就把原来的redux-thunk
替换成redux-saga
了,当然,现在我们还不能使用,我们还需要继续配置sagas.js
文件。
创建sagas.js文件并引入
redux-saga
希望你把业务逻辑单独写一个文件,这里我们在/src/store/
文件夹下建立一个sagas.js
文件。
function* mySaga() {} export default mySaga;
创建好以后直接引入到index.js
里。
import mySagas from './sagas'
然后执行 run 方法,让saga
运行起来。
sagaMiddleware.run(mySagas)
为了方便你学习,这里给出/src/store/index.js
的全部内容。
import { createStore , applyMiddleware ,compose } from 'redux' // 引入 createStore 方法 import reducer from './reducer' import createSagaMiddleware from 'redux-saga' import mySagas from './sagas' const sagaMiddleware = createSagaMiddleware(); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose const enhancer = composeEnhancers(applyMiddleware(sagaMiddleware)) const store = createStore( reducer, enhancer) sagaMiddleware.run(mySagas) export default store
现在已经完全替换成redux-saga
了,所以以前在TodoList.js
中的代码需要删除,不删除就会报错。主要删除componentDidMount
声明周期函数里的代码。 这样redux-saga
的安装和配置就算完成了,之后我们就可以编写中间件了。其实这个配置一般在项目中也只需要作一次,你完全可以收藏网页,然后需要时回来看一下就可以了。
码云笔记 » P17:Redux进阶-Redux-saga的安装和配置