简体   繁体   中英

Why console.log not return the value 1?

From my database I have set one person to be "banned" but instead of printing the value "1" it leaves it empty and even when the value is 0 it still leaves it empty.

 for (const dataItem of res.data.data) {

  var IsBanned = 0 ;
  if(dataItem.banned === true){ 
  this.setState({IsBanned: this.state.count +1})
  console.log("Local", IsBanned);
  } 
}

console.log

any advice is appreciated

this.setState() is async function so it does take some time to update value in state.

You can utilise 2nd argument of setState which is callback

this.setState({IsBanned: this.state.count +1},()=>console.log("Local", this.state.IsBanned);)

Here you have taken isBanned as local variable, but trying to update it as state variable. So you first need to decide whether to keep it in state or in local.

1.This code may fail to update the counter:

this.setState({IsBanned: this.state.count +1})
console.log("Local", IsBanned);

2.You have to use this because setState() that accepts a function rather than an object.

this.setState((state) => ({IsBanned: state.counter + 1}));

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