简体   繁体   中英

React Native Updating State with this.setState

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})
    }

Hi please check below code.

this.setState((prev) => {
  prev.data.datasets[0].data[0] = response.data.rates.AUD;
  return {
    ...prev
  };
});

Use setState like this:

this.setState((prev) => {
  prev.data.datasets[0].data[0] = response.data.rates.AUD;
  return {
    ...prev
  };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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