Update an array in React state?

Asked

Viewed 448 times

-1

I’m trying to extract the elements from a array and move on to another array in the state more still unsuccessful, my code is like this:

this.state = {lista[]};
//(No metodo)
let v = "";
for(var j=0;j<=vetor.lenght-1;j++){    
     v = vetor[j];
     this.state.setState((state) => { state.lista.concat(v); }); 
}

What I’m doing wrong?

  • Next guy copy a array and create another or even add another is simple but, your current code does not help, could improve?

1 answer

0

Well, my approach to your problem would be as follows::

//(No construtor)
    this.state = {lista : []};

//(No metodo)
    let arr_temp = this.state.lista;
    for(var j=0;j<=vetor.lenght-1;j++){    
      arr_temp.push(vetor[j])
    }
    arr_temp = [...arr_temp];
    this.setState({lista: arr_temp})
  

You could also do this without it, using the spread to join the two arrays in a temporaria within the method, and then set the state, but it’s up to you

  • Did not function.... it returns list.lenght = 0.

  • Ué, return list.length where? try using a.log console like this: this.setState({list: arr_temp}, ()=>console.log(this.state.list))

  • I’m testing the result like this: console.log("LIST SIZE : "+this.state.list.length) and gives ZERO...

  • @Ninja2112 put the test in the callback of setstate, how did I answer there? just to make sure you’re getting the state dps of it change

  • Yes.... Same thing

  • strange, there is no complicated logic behind this code, it should be doing what you want. There is no problem with the variable vector by chance?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.