简体   繁体   English

如何在fetchData中为状态变量赋值?

[英]How to assign value to a state variable inside fetchData?

This is fetchData function used in my ReactJS class. 这是我的ReactJS类中使用的fetchData函数。 It makes a call to API which returns an integer. 它调用API,该API返回一个整数。

fetchData = () => {

    const url = "http://localhost:8000?"+
      'mytime='+this.state.mytime+
      '&mytype='+this.state.mytype;

    fetch(url, {
      method: "GET",
      dataType: "JSON",
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      }
    })
    .then((resp) => {
      return resp.json()
    })
    .then((data) => {
      this.setState({
          chartData: [...this.state.chartData, {field1: this.state.field1, field2: data.field2}]
      })
    })
    .catch((error) => {
      console.log(error, "catch the hoop")
    })
};

I don't know how to assign this result ( data.field2 ) to this.state.field2 = data.field2 . 我不知道如何将此结果( data.field2 )分配给this.state.field2 = data.field2 How can I do it inside this code part: 我如何在此代码部分中做到这一点:

.then((data) => {
      this.setState({
          chartData: [...this.state.chartData, {field1: this.state.field1, field2: data.field2}]
      })
    })

state = {
  chartData: ['A', 'B',
    {
      field1: 'C',
      field2: ''
    }
  ]
}
.then((data) => {
 const {chartData} = this.state;
 console.log(chartData[2].field2=data)
})

I try to set with this condition 我尝试设置此条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM