问题
0
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})
}
回答1:
This might help
this.setState({data: {
...this.state.data,
datasets: [
{
label: this.state.data.datasets[0].label,
data: response.data.rates.AUD,
}
],
});
回答2:
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,
}
],
});
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
来源:https://stackoverflow.com/questions/65562408/react-native-updating-state-with-api