gpt4 book ai didi

javascript - 如何在使用已更新的依赖值分派(dispatch)操作后更新 api 调用

转载 作者:行者123 更新时间:2023-12-02 22:15:09 25 4
gpt4 key购买 nike

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

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

最佳答案

使用 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
}
}

关于javascript - 如何在使用已更新的依赖值分派(dispatch)操作后更新 api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59413204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com