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

时间:2019-01-13 23:36:06

标签: javascript html reactjs

这是我的ReactJS类中使用的fetchData函数。它调用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")
    })
};

我不知道如何将结果(data.field2)分配给this.state.field2 = data.field2。我如何在此代码部分中做到这一点:

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

1 个答案:

答案 0 :(得分:0)

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

我尝试设置此条件