分派具有相关值的动作后,如何更新api调用

时间:2019-12-19 16:02:10

标签: javascript reactjs redux react-redux

我有以下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;

现在,我想做的是,一旦在以下位置之后用新的 fromCurrency 属性更新了我的Redux存储,就会触发该服务调用:

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

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

1 个答案:

答案 0 :(得分:1)

使用反应生命周期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
  }
}