React 状态管理 - Redux 进阶(上)

优化使用Redux,让应用更高效

在react中修改全局state就是个同步的过程。

通过dispatch具体的类型,立刻改变state,和拉取服务端数据的过程是异步的。这个是dispatch没有具体结果

Redux异步

Redux Middleware

  • Redux的插件机制,使得Redux默认的同步Action扩展支持异步Action
export function updateName(params) {
    return {
        type:'UPDATE_NAME',
        payload: params    
    }
}
dispatch(updateName('云'))

 异步

function queryUserInfo(params) {
    return (dispatch, getState) {
        fetch({
            // ...        
        }).
        then((res) => {
            dispatch({
               type:'FETCH_DATA_SUCCESS',
        		payload: res.data             
            })        
        })
    }
}

1.applyMiddleware接收一系列插件。每个插件(middleware)都会以dispatch和getState作为参数,并返回一个函数。该函数会被传入下一个插件中,直到调用结束。

import { 
    createStore,
    combineReducers, applyMiddleware,
} from 'redux';
// 处理异步的插件
import thunk from 'redux-thunk';

export default createStore(
    combineReducers,
    applyMiddleware(...[thunk, otherMiddleware])
);

Reducer起始,插件执行一遍收尾,改变Reducer

@/src/store/index.js
import { createStore, applyMiddleware } from 'redux';
// 处理异步数据的redux插件
import thunk from 'redux-thunk';
import reducers from '@/reducer';

export default createStore(
  reducers,
  applyMiddleware(thunk),
);
 /src/actions/home/index.js
import * as types from '../mutation-types';
// 请求数据方法
export function queryName(params) {
  return {
    type: types.QUERY_GLOBAL_NAME,
    payload: params,
  };
}
// 改变数据方法
export function updateName(params) {
  return {
    type: types.UPDATE_GLOBAL_NAME,
    payload: params,
  };
}
// 异步请求数据
export function queryAsyncName(params) {
  return (dispatch, getState) => {
    setTimeout(() => {
        console.log('getState', getState())
      dispatch({
        type: types.QUERY_GLOBAL_NAME,
        payload: params,
      });
    }, 2000);
  };
}
// 异步修改数据
export function asynUpdatecName(params) {
  return async (dispatch) => {
    setTimeout(() => {
        // 异步操作中会执行同步操作的方法,只是延迟了。
      dispatch(updateName(params));
    }, 3000);
  };
}
@/src/containers/home/index.jsx
/* eslint-disable react/no-unused-prop-types */
import React, { Component } from 'react';
// react 的类型检测
import PropTypes from 'prop-types';
import { updateName, queryAsyncName, asynUpdatecName } from '@/actions/home';
import { connect } from 'react-redux';
@connect(
  (state) => state.homeReducer,
  (dispatch) => ({
    updateName: (params) => dispatch(updateName(params)),
    queryAsyncName: (params) => dispatch(queryAsyncName(params)),
    asynUpdatecName: (params) => dispatch(asynUpdatecName(params)),
  })
)
export default class Home extends Component {
  handleClick = () => {
    const {
      // updateName,
      // queryAsyncName,
      asynUpdatecName,
    } = this.props;
    // console.log(updateName);
    asynUpdatecName('异步云');
  };
  render() {
    const { homeName } = this.props;
    return (
      <div>
        <div>{homeName}</div>
        <button type='button' onClick={this.handleClick}>
          更改
        </button>
      </div>
    );
  }
}
// react 的类型定义,类型声明,检测非常重要
Home.propTypes = {
  homeName: PropTypes.string,
  updateName: PropTypes.func,
  queryAsyncName: PropTypes.func,
  asynUpdatecName: PropTypes.func,
};

Home.defaultProps = {
  homeName: '',
  updateName: () => ({}),
  queryAsyncName: () => ({}),
  asynUpdatecName: () => ({}),
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值