简体   繁体   中英

React console.log not showing state array values

In React i have a function called addOrder that adds object with parameter values to state called data. When i try to console.log(this.state.data) i get an empty array for some reason. When i click button that calls addOrder function again i get array that contains objects with parameter values. Why doesn't console.log show me array values the first time i click button?

import React, { Component } from 'react';



class App extends Component {
  constructor(){
    super()
    this.state = {
      data:[]
    }

  }


addOrder(parameter1, parameter2, parameter3){
  this.setState({
    data:this.state.data.concat(
        {
         one:parameter1,
         two:parameter2,
         three:parameter3
        }
     )          
  });

  console.log(this.state.data);
}


  render() {

    return (
      <div>
            <button onClick={() => this.addOrder('1','2','3')}>ok</button>
      </div>
    )
  }
}

export default App;

I expected console.log to show [{one: "1", two: "2", three: "3"}], but instead i got empty array []

Call to setState() is asynchronous So javascript compiler does not wait for setState to finish. So it reaches the next line and print your console.log statement and since at this point of time your state is not updated and the data array is empty it prints the empty array to the console.

setState() also comes with a callback which executes when you state has been updated.

You can try this

this.setState({
data:this.state.data.concat(
    {
     one:parameter1,
     two:parameter2,
     three:parameter3
    }
 )          
}, () => console.log(this.state.data));

Will work fine now

addOrder(parameter1, parameter2, parameter3){
 this.setState({
  data:this.state.data.concat(
    {
     one:parameter1,
     two:parameter2,
     three:parameter3
    }
   )          
  },()=>console.log(this.state.data));
 }

try this way

setState is an asynchronous function. The second argument of setState is a callback so you can use it to know when the function has finished.

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