用Api反应本机更新状态 [英] React Native Updating State with Api

查看:44
本文介绍了用Api反应本机更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   0

我正在尝试从API更新状态数据值(data:[]).问题是从突出显示这一行的this.setState({data.datasets [0] .data.data:response.data.rates.AUD})

Hi I'm trying to update the state data value (data:[]) from API. the issue is from the line highlighted this.setState({data.datasets[0].data.data:response.data.rates.AUD})

    import React from 'react';
import {Bar} from 'react-chartjs-2';
import axios from 'axios';

class App extends React.Component {

constructor(props) {
    super(props)
    this.state = {
        data: {
            labels:["UK"],
            datasets:[
            {label:"Dev Test",data:[]}
            ]
}}

this.test = this.test.bind(this)
}
 async test() {
    const response = await axios.get("https://api.exchangeratesapi.io/latest")
    this.setState({data.datasets[0].data[0]:response.data.rates.AUD})
    
}

推荐答案

我相信问题在于,您正在尝试更新对象内部属性的值,而您必须对整个 data 属性:

I believe the problem is that you are trying to update a value for a property inside an object and you have to do it for the whole data property:

this.setState({data: {
  ...this.state.data,
  datasets: [
    {
      label: this.state.data.datasets[0].label,
      data: response.data.rates.AUD,
    }
  ],
});

我实际上不认为我编写的这段代码是正确的,因为我不了解您的数据结构,但想法是您必须一起更新整个 data 状态,保留要保留的旧数据并更新新数据.您不能直接更新对象数组中的属性.但是,您可以单独更新第一级属性.检查以下内容: https://itnext.io/react-setstate-usage-and-gotchas-ac10b4e03d60

I don't actually think this code I wrote is correct because I don't understand the structure of your data, but the idea is that you have to update the whole data state all together, keeping old data you want to keep and updating new data. You can't update directly a property in an array in an object. You can update separately first level properties though. Check this: https://itnext.io/react-setstate-usage-and-gotchas-ac10b4e03d60

这篇关于用Api反应本机更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆