redux的中间件

概念

redux的中间件就是用来处理reducer和actions之间应用,可以处理reducer和actions之间的数据流,实现如异步action,日志输出等操作.

在redux中通过applyMiddleware方法使用中间件

常用的异步处理action中间件有redux-thunk,redux-sage.

redux-logger:提供日志输出

使用例子

redux-thunk的使用例子

//store/index.js文件

import reduxThunk from "redux-thunk";
const store = createStore(reducer,composeWithDevTools(applyMiddleware(reduxThunk)));

//store/reducer纯函数

const defaultState={
  login:{} } export
default (state=defaultState,actions)=>{   switch(actions.type){     case 'LOGIN':       ...     }   return state; }

//组件发送action

import {LoginActions} from '@api/login';

import {connect} from 'react-redux';

<Form

  name="normal_login"

  className="login-form"

  initialValues={{ remember: true }}

  onFinish={this.props.onFinish}

>

const mapDispatchToProps=(dispatch)=>({

  // 提交内容{username:,password:}

  onFinish(values){

    dispatch(LoginActions(values))

  }

})

export default connect(null,mapDispatchToProps)(LoginInput)

//redux-thunk定义异步的action

import api from './api';
import http from '@utils/http.js';
// redux-thunk异步:让action是一个函数,并且返回一个函数,返回函数内部有dispatch参数,通过内部函数结合async+await实现异步
//LoginActions是一个action,外部需要dispatch调用
export const LoginActions=(params)=>{
  //请求后台接口
  return async (dispatch)=>{
    let result=await http.post(api.login,params);
    dispatch({
      type:'LOGIN',
      data:result
    })
  }
}
原文地址:https://www.cnblogs.com/liuXiaoDi/p/12594262.html