首页 > 解决方案 > 如何在使用更新的依赖值调度操作后更新 api 调用

问题描述

我有以下 App.js:

  constructor(props) {
    super(props);
    this.props.setLoading();
  }

  componentDidMount(){
    this.convert();
  }

  changeFromCurr = (event) => {
    this.props.setFromCurrency(event.target.value);
    this.convert();
  }

  changeToCurr = (event) => {
    this.props.setToCurrency(event.target.value);
    this.convert();
  }

  changeAmount = (event) => {
    this.props.setValue(event.target.value);
  }

  convert = () => {
    return this.props.convertCurr(this.props.fromCurrency,this.props.toCurrency,this.props.value);
  }

  render() {
    const {fromCurrency, toCurrency, value, result} = this.props;
    return (
      <div>
        <CurrencyForm
          fromCurrency={fromCurrency}
          toCurrency={toCurrency}
          amount={value}
          changeFromCurr={this.changeFromCurr}
          changeToCurr={this.changeToCurr}
          changeAmount={this.changeAmount}
          result={result}
        />

我对 convertCurr 的要求是:

mport convertCurrency from '../service';
import {requestApi, receiveRes, accessDenied, apiError} from './currencyActions';

function convertCurr(from,to,amt) {
    return dispatch => {
        dispatch(requestApi());
        convertCurrency(from,to,amt)
        .then(res => res)
        .then(res => {
            if(res.error) {
                throw(res.error);
            }else if(res.accessDenied){
                dispatch(accessDenied(res.accessDenied));
            }
            dispatch(receiveRes(res.data.rates[to]));
            return res.result;
        })
        .catch(error => {
            dispatch(apiError(error));
        })
    }
}

调用此服务:

import axios from 'axios';


let convertCurrency = async (from,to,amt) => {
    const API_KEY= `b688884ff57c3e17139e632b5f852755`;
    const convertUrl = `http://data.fixer.io/api/latest?
    access_key=${API_KEY}&base=${from}&symbols=${to}`
  try {
    const response = await axios.get(convertUrl);
    console.log(response);
    return response;
  }
  catch (err) {
    console.log('fetch failed', err);
  }
}

export default convertCurrency;

现在我想做的是在我的 Redux 存储在以下之后使用新的fromCurrency属性更新后触发此服务调用:

this.props.setFromCurrency(event.target.value);

更新状态,我希望使用新值调用服务。任何帮助将非常感激。

标签: javascriptreactjsreduxreact-redux

解决方案


使用 react 生命周期componentDidUpdate

componentDidUpdate(prevProps, prevState) {
  if (yourMethodToCheckIfNotEqual(prevProps.fromCurrency, this.props.fromCurrency)) {
    // Fire your service call
    // Notice that if your service call changes fromCurrency above may cause infinite loop
  }
}

推荐阅读