Calling setState in a loop only updates state 1 time

前端 未结 5 2220
故里飘歌
故里飘歌 2020-11-27 21:56

Is there a reason that calling setSate() in a loop would prevent it from updating the state multiple times?

I have a very basic jsbin that highlights th

相关标签:
5条回答
  • 2020-11-27 21:57

    I had the same problem. But tried with a little different approach.

    iterateData(data){
      //data to render
       let copy=[];
       for(let i=0;<data.length;i++){
         copy.push(<SomeComp data=[i] />) 
        }
        this.setState({
          setComp:copy
        });
     }
     render(){
       return(
         <div>
           {this.state.setComp}
        </div>
       );
     }
    

    I hope this helps.

    0 讨论(0)
  • 2020-11-27 21:59

    There's a nice way to update state in a loop. Just make an empty variable, set its value to the updated state, call setState(), and pass it this variable:

    const updatedState = {};
    
    if (vars.length) {
      vars.forEach(v => {
        updatedState[v] = '';
        this.setState({
          ...this.state
          ...updatedState,
        });
      });
    }
    
    0 讨论(0)
  • 2020-11-27 22:05

    Basically setState is called asynchronously. It also has a callback function which you can utilise to do something once the state has been mutated. Also if multiple setStates are called one after the other they are batched together as written previously.

    0 讨论(0)
  • 2020-11-27 22:10

    I was able to make your code work, calling setState in the loop by doing the following:

     manyClicks() {
       for (i = 0; i < 100; i++) {
         this.setState({clicks: this.state.clicks += 1})
       }
     }
    enter code here
    

    Hopefully this helps!

    0 讨论(0)
  • 2020-11-27 22:17

    From the React 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.

    Basically, don't call setState in a loop. What's happening here is exactly what the docs are referring to: this.state is returning the previous value, as the pending state update has not been applied yet.

    0 讨论(0)
提交回复
热议问题