简体   繁体   English

用 Api 反应本机更新 State

[英]React Native Updating State with Api

   0

Hi I'm trying to update the state data value (data:[]) from API.嗨,我正在尝试从 API 更新 state 数据值(数据:[])。 the issue is from the line highlighted this.setState({data.datasets[0].data.data:response.data.rates.AUD})问题来自突出显示的行 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})
    
}

This might help这可能会有所帮助

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

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:我认为问题在于您正在尝试更新 object 中的属性值,并且您必须为整个data属性执行此操作:

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

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.我实际上并不认为我写的这段代码是正确的,因为我不了解您的数据结构,但想法是您必须将整个data state 一起更新,保留您想要保留的旧数据并更新新数据数据。 You can't update directly a property in an array in an object.您不能直接更新 object 中数组中的属性。 You can update separately first level properties though.不过,您可以单独更新第一级属性。 Check this:https://itnext.io/react-setstate-usage-and-gotchas-ac10b4e03d60检查这个:https://itnext.io/react-setstate-usage-and-gotchas-ac10b4e03d60

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

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