循环内的setState不会更新状态:React + Typescript

时间:2019-05-10 09:19:33

标签: reactjs setstate

我有一个对象数组,这是一个与用户帐户相对应的状态对象。仅出于验证目的,如果数组内的任何对象属性为空,则将状态对象的验证属性设置为false。由于我正在循环使用for循环,因此setState不会设置数据。

 this.state = {
      accounts: [{firstname:"",lastname:"",age:""}],
      validated: true
 };


onAdd = () => {

    let { accounts,validated } =  this.state;
    for(let i=0; i< accounts.length; i++){
      if(accounts[i].firstname === '' || accounts[i].age === '')
      {
        this.setState({validated: false},() => {}); // value is not getting set
        break;
      }
    }
    if(validated)
    {
      // some other operation 
      this.setState({validated: true},() => {});
    }
  }

render(){

   let { validated } =  this.state;
   return(
     {validated ? <span>Please fill in the details</span> : null}
       //based on the validated flag displaying the error message
   )
}

3 个答案:

答案 0 :(得分:2)

尝试通过状态单独检查数组,并根据数据是否丢失来确定临时变量为true还是false。然后根据temp变量可以相应地设置状态。

让我知道这是否可行:

onAdd = () => {

  let { accounts,validated } =  this.state;
  let tempValidate = true; //assume validate is true
  for(let i=0; i< accounts.length; i++){
    if(accounts[i].firstname === '' || accounts[i].age === '')
    {
      //this loop will check for the data validation, 
      //if it fails then you set the tempValidate to false and move on
       tempValidate = false
      break;
    }
  }

  // Set the state accordingly
  if(tempValidate)
  {
    this.setState({validated: true},() => {});
  } else {
    this.setState({validated: false},() => {});
  }
}

答案 1 :(得分:1)

setStateasync函数。因此它不会循环工作。

docs

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

另请参阅this

答案 2 :(得分:1)

您的代码中存在多个问题。首先,this.setState是异步的,因此您不能说它何时真正执行。

所以如果你打电话

this.setState({validated: false},() => {});

this.state.validated即刻为假之后,您不能依靠它。

因此,在您致电this.setState使其成为validated == false之后,请检查:

if(this.state.validated)
{
  // some other operation 
  this.setState({validated: true},() => {});
}

可能是对还是错。

但是在您的代码中,您将在方法开始时提取validated(在if条件中使用的内容)。这意味着validated更改时this.state不会更改。

您可能想使用已经添加的回调(() => {})在状态更改后执行其他一些操作,或者只使用常规变量而不是与状态相关的内容。

赞:

tmp = true;

for-loop {
  if(should not validate) {
    tmp = false;
    this.setState({validated: false});
    break;
  }

if(tmp) {
  this.setState({validated: true},() => {});
}
相关问题