Why can't I push values in my state array in react.js?

前端 未结 5 992
后悔当初
后悔当初 2021-01-15 09:40

I can add 1 item to the array it logs [\"50\"] in the console. But when I try to add a second value I get this error \"currentScores.push is not a f

5条回答
  •  猫巷女王i
    2021-01-15 10:28

    Two things, when you make use of push it doesn't return a new array. Make use of concat and bind the value to the addUser function.

    Also wrap your elements inside a single div and write your console.log() statement to output the state value in the callback function of setState since it takes some time to mutate

     class Scores extends React.Component {
    
          constructor() {
            super();
            this.addScore = this.addScore.bind(this);
            this.handleScoreChange = this.handleScoreChange.bind(this);
            this.state = {
              scores: [],
              scoreInput: '',
            };
          }
    
          addScore() {
            const currentScores = this.state.scores;
            const newScores = currentScores.concat(this.state.scoreInput);
            this.setState({ scores: newScores }, function(){
              console.log(this.state.scores);
            });
            
          }
    
          handleScoreChange(e) {
            this.setState({ scoreInput: e.target.value });
          }
    
          render() {
            const scores = this.state.scores;
            return (
                    
    ); } } ReactDOM.render(, document.getElementById('app'));
    
    
    

提交回复
热议问题