第一个 fetch 调用 returns 空数组调用但在第二个上有效,依此类推?
First fetch call returns empty array call but works on the second and so on?
如上所述,每当我获取数据以将值设置为状态时,它只会在我第二次输入收费金额、货币和 fysigned 字段时设置状态。我的主要问题是为什么我第一次在这些字段中输入值时它会获取一个空数组? 第一次取值未定义
代码
setUSDValue() {
const { AmountCharged, Currency, FYSigned} = this.state;
if(AmountCharged && Currency && FYSigned)
{
fetch(`http://ca-fpscfb2:2000/USDValueExchangeRateValue?rateYear=${FYSigned}&USD=${Currency}&CAD=${Currency}&INR=${Currency}&GBP=${Currency}`)
.then(response => response.json().then(response =>
this.setState(
{
exchangeRateVal: response.data
}
)))
.then(
this.state.exchangeRateVal && this.state.exchangeRateVal.map((rate) =>
(
this.setState({
USDValue: rate.USD
})
))
)
}
}
问题是调用 this.setState
时状态不会立即更新。如果在状态更新后直接需要该代码 运行,请尝试使用回调函数:
setUSDValue() {
const { AmountCharged, Currency, FYSigned} = this.state;
if(AmountCharged && Currency && FYSigned)
{
fetch(`http://ca-fpscfb2:2000/USDValueExchangeRateValue?rateYear=${FYSigned}&USD=${Currency}&CAD=${Currency}&INR=${Currency}&GBP=${Currency}`)
.then(response => response.json().then(response =>
this.setState(
{
exchangeRateVal: response.data
},
() =>
this.state.exchangeRateVal.map((rate) =>
(
this.setState({
USDValue: rate.USD
})
))
)))
}
如上所述,每当我获取数据以将值设置为状态时,它只会在我第二次输入收费金额、货币和 fysigned 字段时设置状态。我的主要问题是为什么我第一次在这些字段中输入值时它会获取一个空数组? 第一次取值未定义
代码
setUSDValue() {
const { AmountCharged, Currency, FYSigned} = this.state;
if(AmountCharged && Currency && FYSigned)
{
fetch(`http://ca-fpscfb2:2000/USDValueExchangeRateValue?rateYear=${FYSigned}&USD=${Currency}&CAD=${Currency}&INR=${Currency}&GBP=${Currency}`)
.then(response => response.json().then(response =>
this.setState(
{
exchangeRateVal: response.data
}
)))
.then(
this.state.exchangeRateVal && this.state.exchangeRateVal.map((rate) =>
(
this.setState({
USDValue: rate.USD
})
))
)
}
}
问题是调用 this.setState
时状态不会立即更新。如果在状态更新后直接需要该代码 运行,请尝试使用回调函数:
setUSDValue() {
const { AmountCharged, Currency, FYSigned} = this.state;
if(AmountCharged && Currency && FYSigned)
{
fetch(`http://ca-fpscfb2:2000/USDValueExchangeRateValue?rateYear=${FYSigned}&USD=${Currency}&CAD=${Currency}&INR=${Currency}&GBP=${Currency}`)
.then(response => response.json().then(response =>
this.setState(
{
exchangeRateVal: response.data
},
() =>
this.state.exchangeRateVal.map((rate) =>
(
this.setState({
USDValue: rate.USD
})
))
)))
}