Redux 的核心概念其实很简单: 将需要修改的 state 都存入到 store 里, 发起一个 action 用来描述发生了什么, 用 reducers 描述 action 如何改变 state tree . 创建 store 的时候需要传入 reducer, 真正能改变 store 中数据的是 store.dispatch API.
1. 概念
dispatch 一个 action 之后, 到达 reducer 之前, 进行一些额外的操作, 就需要用到 middleware. 你可以利用 Redux middleware 来进行日志记录, 创建崩溃报告, 调用异步接口或者路由等等.
换言之, 中间件都是对 store.dispatch() 的增强
2. 中间件的用法
- import { applyMiddleware, createStore } from 'redux';
- import thunk from 'redux-thunk';
- const store = createStore(
- reducers,
- applyMiddleware(thunk)
- );
直接将 thunk 中间件引入, 放在 applyMiddleware 方法之中, 传入 createStore 方法, 就完成了 store.dispatch() 的功能增强. 即可以在 reducer 中进行一些异步的操作.
3.applyMiddleware()
其实 applyMiddleware 就是 Redux 的一个原生方法, 将所有中间件组成一个数组, 依次执行.
中间件多了可以当做参数依次传进去
- const store = createStore(
- reducers,
- applyMiddleware(thunk, logger)
- );
- 4.redux-thunk
分析 redux-thunk 的源码 node_modules/redux-thunk/src/index.JS
- function createThunkMiddleware(extraArgument) {
- return ({ dispatch, getState }) => next => action => {
- if (typeof action === 'function') {
- return action(dispatch, getState, extraArgument);
- }// 欢迎加入全栈开发交流圈一起学习交流: 864305860
- return next(action);
- };// 面向 1-3 年前端人员
- } // 帮助突破技术瓶颈, 提升思维能力
- const thunk = createThunkMiddleware();
- thunk.withExtraArgument = createThunkMiddleware;
- export default thunk;
redux-thunk 中间件 export default 的就是 createThunkMiddleware() 过的 thunk, 再看 createThunkMiddleware 这个函数, 返回的是一个柯里化过的函数. 我们再翻译成 ES5 的代码容易看一点,
- function createThunkMiddleware(extraArgument) {
- return function({ dispatch, getState }) {
- return function(next){
- return function(action){
- if (typeof action === 'function') {
- return action(dispatch, getState, extraArgument);
- }
- return next(action);
- };// 欢迎加入全栈开发交流圈一起学习交流: 864305860
- }// 面向 1-3 年前端人员
- }// 帮助突破技术瓶颈, 提升思维能力
- }
可以看出来 redux-thunk 最重要的思想, 就是可以接受一个返回函数的 action creator. 如果这个 action creator 返回的是一个函数, 就执行它, 如果不是, 就按照原来的 next(action) 执行.
正因为这个 action creator 可以返回一个函数, 那么就可以在这个函数中执行一些异步的操作.
例如:
- export function addCount() {
- return {type: ADD_COUNT}
- }
- export function addCountAsync() {
- return dispatch => {
- setTimeout( () => {
- dispatch(addCount())
- },2000)
- }// 欢迎加入全栈开发交流圈一起学习交流: 864305860
- }// 面向 1-3 年前端人员
- // 帮助突破技术瓶颈, 提升思维能力
addCountAsync 函数就返回了一个函数, 将 dispatch 作为函数的第一个参数传递进去, 在函数内进行异步操作就可以了.
结语
感谢您的观看, 如有不足之处, 欢迎批评指正.
来源: http://www.qdfuns.com/article/51117/0ea51af21f6febf8c098c2ad75687a34.html