React中的单项数据流

本文详细介绍了在React应用中如何使用dva进行状态管理和路由操作,结合apiCreator工具进行接口请求。当组件接收到新的props时,会比较新旧数据并更新状态,同时展示错误处理逻辑。通过connect和withRouter高阶组件实现组件与全局状态及路由的连接。
摘要由CSDN通过智能技术生成

背景:

 页面调用接口:

import { connect } from 'dva';
import { withRouter, routerRedux, Link } from 'dva/router'; // push主要用来跳转页面

const mapStateToProps = state => ({
  // 用来接收后端的返回数据
  list: state.businesssequence.fundAccountSearchResult,
  isLoading: state.loading.effects[actionType] || false, // 判断是否在加载数据
  matchfoundaccountResult: state.businesssequence.matchfoundaccountResult,
  dictBusinessSequenceResult: state.businesssequence.dictBusinessSequenceResult,
});

const mapDispatchToProps = {
  getList: getListFunction(true),
  fundAccountDelete: query => ({
    type: 'businesssequence/fundAccountDelete',
    payload: query || {},
  }),
  matchfoundaccount: query => ({
    type: 'businesssequence/matchfoundaccount',
    payload: query || {},
  }),
  dictBusinessSequence: query => ({
    type: 'businesssequence/dictBusinessSequence',
    payload: query || {},
  }),
  push: routerRedux.push,
};

@connect(
  mapStateToProps,
  mapDispatchToProps
)
@withRouter
class fundCompanyTable extends PureComponent {

   componentDidMount() {
    const { defaultQuery} = this.state;
    this.props.getList(defaultQuery); // 页面调用后端接口
  }

componentWillReceiveProps(nextProps) {
    const {
      location: { key, pathname },
      isLoading,
      matchfoundaccountResult, // 对应接口返回的数据
    } = nextProps;
    const { searchQuery} = this.state; 
    const currentPath = _.last(pathname.split('/'));
    if ( // nextprops里面新数据和this.props里面老数据进行对比
      matchfoundaccountResult !== this.props.matchfoundaccountResult &&
      currentPath === 'fundCompanyTable'
    ) {
      if (String(matchfoundaccountResult.retCode) === '0') {
        message.success(matchfoundaccountResult.message || '匹配成功');
        this.props.getList(searchQuery );
      } else {
        message.error(matchfoundaccountResult.message || '匹配失败');
      }
    }
    if (
      !isLoading &&
      key !== this.props.location.key && // key用来判断切换之后首次到这个页面
      location.pathname.indexOf('fundCompanyTable') > 0 &&
      currentPath === 'fundCompanyTable'
    ) {
      this.props.getList(searchQuery );
    }
  }

  handleErrorModal = () => {
    const { push } = this.props;
    push('/index'); // push用来跳转到/index的路径下 
  };


}

model.js 里面定义方法的变量空间,获取后端的返回值,放入state.

import api from '../api/businesssequence'; // 调用api文件夹定义的方法

export default {
  namespace: 'businesssequence',
  state: {
   fundAccountSearchResult: {}, // 接收后端的返回数据,存入state
  },

  reducers: {
      fundAccountSearchSuccess(state, action) {
      const {
        payload: { response },
      } = action;
      return {
        ...state,
        fundAccountSearchResult: response || {},
      };
    },

  },

  effects: {
    *fundAccountSearch({ payload: query }, { call, put }) {
      const response = yield call(api.fundAccountSearch, query) || {};
      yield put({
        type: 'fundAccountSearchSuccess',
        payload: { response: response || {}, query },
      });
    },

   },


}

api文件夹定义接口的请求方式。

import api from '@/utils/apiCreator'; // 引入工具类apiCreator中写好的调用请求方式

export default {
 fundAccountSearch: query => api.get('/galaxy/taurus/fundaccount/query', query),
// fundAccountSearch: query => api.post('/galaxy/taurus/fundaccount/query', query),
}

utils工具类封装的方法。

import _ from 'lodash'; // 调用lodash里面的方法
import request from '@/utils/request';
import { getLanguage, queryToString } from './helper';

export default (function createApi() {
  const apiPrefix = '/galaxy/webapi'; // api前缀

  // 如果没有前缀,自动补上
  const padPrefix = url => {
    if (url.indexOf(apiPrefix) === -1) {
      return apiPrefix + url;
    }
    return url;
  };

  // 授权信息: empId, deviceId, token
  let authInfo = {};
  /* let iv_user = getEmpId();
  let authInfo = {
    iv_user,
  }; */

  return {
    get(url, query) {
      let finalUrl = padPrefix(url);
      const queryString = _.isEmpty(query) ? '' : queryToString(query);
      const clientKey = Math.random() // 解决IE浏览器接口调用返回304
        .toString(36)
        .substr(2);
      finalUrl = queryString
        ? `${finalUrl}?${queryString}&randomKey=${clientKey}`
        : `${finalUrl}?randomKey=${clientKey}`;
      const headers = this.getHeaders({
        ...authInfo,
        langCode: this.langCode(),
      });

      return request(finalUrl, {
        method: 'GET',
        headers,
      });
    },

    /**
     * @param {string} url API url
     * @param {Object} query 请求参数
     *
     * @return {Promise}
     */
    post(url, query) {
      const finalUrl = padPrefix(url);
      const headers = this.getHeaders({
        ...authInfo,
        'Content-Type': 'application/json',
        langCode: this.langCode(),
      });
      return request(finalUrl, {
        method: 'POST',
        headers,
        body: JSON.stringify(query),
      });
    },

  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值