javascript - 如何在使用更新的依赖值调度操作后更新 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);
更新状态,我希望使用新值调用服务。任何帮助将非常感激。
解决方案
使用 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 - 如何在调用渲染方法之前从 API 获取数据?(反应,护照,快递)
- php - 尝试多种方法和教程后 Composer PSR-4 自动加载不起作用
- angular - 新选项卡 ionic starter 项目在 ios 模拟器和 ios 设备上简单崩溃的问题。但如果使用离子服务则有效
- javascript - 输入视频文件 avi , wmv 时获取视频时长
- git - 避免在分叉存储库上合并提交的原因是什么?
- firebase - 从下拉按钮 Flutter 传递数据
- cmake - 使用 CMake 添加带有生成的源文件的库
- python - 为什么我只能下载 51 张图片而不是 151 张图片,为什么没有显示错误?
- javascript - 如何在 JavaScript 中找到等于给定总和的三元组的所有可能组合?(“星星和酒吧”或“球和垃圾箱”问题)
- python - 在熊猫中创建总列的百分比