【问题标题】:First fetch call returns empty array call but works on the second and so on?第一个 fetch 调用返回空数组调用,但在第二个等上工作?
【发布时间】:2018-11-15 05:16:18
【问题描述】:

如上所述,每当我获取数据以将值设置为状态时,它只会在我第二次输入收费金额、货币和已签名字段时设置状态。我的主要问题是为什么我第一次在这些字段中输入值时它会获取一个空数组? 第一次未定义值

代码

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
      })
    ))  
  )
}




}

【问题讨论】:

    标签: reactjs fetch fetch-api


    【解决方案1】:

    问题是调用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
          })
        ))  
    
        )))
    }
    

    【讨论】:

    • 我在尝试回调时遇到错误,我得到这个 作为回调传递的无效参数。期望一个函数。而是收到:Invalid argument 作为回调传递的行上。期望一个函数。而是收到:
    • @bobb1213131 我更新了我的回复,现在应该可以使用了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多