试图设置 react-highcharts 的状态,但它不起作用?

trying to set the state of react-highcharts, but it isn't working?

如题所述,如何在react for highcharts中设置状态值的数据? this.state.number的值为0/undefined

代码

getFirstMonthOpenEnhancements(){
    fetch(`http://ca-fpscfb2:4000/1stMonthOpenedEnhancements?airline=${this.state.airlineName}&product=${this.state.airlineProduct}`)
    .then(response => response.json())
    .then( response =>  
        this.setState(
        { 
          number: parseInt(response.data.total) 
        }
    ))

    .catch(err => console.error(err))
  }
 componentDidMount(){
    this.getFirstMonthOpenEnhancements();
    let chart = this.refs.chart.getChart();
    chart.series[4].setData([this.state.number, 4, 4, 4]);
 }

this.state.number 属性 是未定义的,因为你的 API 请求是异步的,所以当你要求 this.state.number 的值时,它是未定义的,因为你的 API 电话还没回。

有几个不同的解决方案,但在我看来最优雅的是返回承诺。

getFirstMonthOpenEnhancements(){
    return new Promise((resolve, reject) => {
        fetch(`http://ca-fpscfb2:4000/1stMonthOpenedEnhancements?airline=${this.state.airlineName}&product=${this.state.airlineProduct}`)
        .then(response => response.json())
        .then( response =>  
            return resolve(parseInt(response.data.total))
        ))
        .catch((err) => { return reject(err) });
    });
}

componentDidMount(){
    this.getFirstMonthOpenEnhancements()
    .then((someNumber) => {
        let chart = this.refs.chart.getChart();
        chart.series[4].setData([someNumber, 4, 4, 4]);
        this.setState({ number: someNumber });
    })
    .catch((err) => { console.log(err); });
 }