React之Redux (三) 中间件和异步

一 为什么要用中间件

从前两篇文章中可以知道,更新Redux中状态的流程是:action -> reducer -> new state。
那么问题来了。每次action被触发(dispatch)。reducer就会同步地对store进行更新,在实际开发项目的时候,有非常多需求都是须要通过接口等形式获取异步数据后再进行更新操作的。怎样异步地对store进行更新呢?
这里就需要新的工具:中间件middleware

二 有哪些中间件

Redux本身提供的Api与功能并不多,可是它提供了一个中间件(插件)机制,能够使用第三方提供的中间件或自己编写一个中间件来对Redux的功能进行增强,比方能够使用redux-logger这个中间件来记录action以及每次action前后的state、使用redux-undo来取消/重做action、使用redux-persist-store来对store进行持久化等等。

三 解决异步action的中间件

要实现异步action,有多个现成的中间件可供选择,这里选择官方文档中使用的redux-thunk这个中间件来实现。
redux-thunk就是dispatch的一个升级,最原始的dispatch方法接收到对象后会将对象传递给store,而用redux-thunk中间件且传递给dispatch的是一个函数的话,那么就不会将函数直接传给store,而是会将函数先执行,执行完毕后,需要调用store的时候,这个函数再去调用store。
1.安装redux-thunk

npm i redux-thunk -S

2.store.js

import {
    
     applyMiddleware, createStore } from 'redux';
import createLogger from 'redux-logger';
const logger = createLogger();

const store = createStore(
  reducer,
  initial_state,
  applyMiddleware(thunk, promise, logger)
);
export default store;

applyMiddleware方法的三个参数就是三个中间件,有的中间件有次序要求,使用前最好查一下文档,如上面的logger就一定要放在最后,否则输出结果会不正确。
3.异步action

export const ACTION_INIT_LIST = value => {
    
    
  return {
    
    
    type: CHANGE_VALUE,
    value
  }
}
//利用redux-thunk 返回方法
export const ACTION_METHOD_INIT = () => {
    
    
  return dispatch => {
    
    
    axios.get('/api/data1').then(res => {
    
    
      console.log(res.data)
      let value = res.data //获取到数据
      let result = ACTION_INIT_LIST(value) //把数据封装到actions里面
      dispatch(result) //然后发射出去
    })
  }
}

四 配置redux浏览器插件

在创建store时在开发环境会链接到redux-devtool,在这个链接过程中可以传递一个参数给当前store实例命名。

import {
    
     createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import reducer from './reducer'
const middleware = [thunk]
const composeEnhancers =
  typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
    
    })
    : compose

const enhancer = composeEnhancers(
  applyMiddleware(...middleware)
  // other store enhancers if any
)
const store = createStore(reducer, enhancer)

export default store

到chrome的开发者工具就能找到对应的一栏
请添加图片描述

猜你喜欢

转载自blog.csdn.net/LittleMoon_lyy/article/details/124563684