ReactJS Array.push function not working in setState

前端 未结 5 1305
粉色の甜心
粉色の甜心 2021-01-17 22:18

I\'m making a primitive quiz app with 3 questions so far, all true or false. In my handleContinue method there is a call to push the users input from a radio fo

5条回答
  •  清酒与你
    2021-01-17 22:59

    I have found a solution. This shoud work for splice and others too. Lets say that I have a state which is an array of cars:

    this.state = {
      cars: ['BMW','AUDI','mercedes']
    };
    this.addState = this.addState.bind(this);
    

    Now, addState is the methnod that i will use to add new items to my array. This should look like this:

      addState(){
    
    let arr = this.state.cars;
    arr.push('skoda');
    this.setState({cars: arr});
    }
    

    I have found this solution thanks to duwalanise. All I had to do was to return the new array in order to push new items. I was facing this kind of issue for a lot of time. I will try more functions to see if it really works for all functions that normally won't. If anyone have a better idea how to achieve this with a cleaner code, please feel free to reply to my post.

提交回复
热议问题