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

前端 未结 5 989
后悔当初
后悔当初 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条回答
  •  悲&欢浪女
    2021-01-15 10:23

    The return value of currentScores.push() is the new number of elements in the array. You then save this in your state which means that scores in your state becomes a number instead of an array.

    You likely want to construct a new array instead since you are working with constant variables:

    const currentScores = this.state.scores;
    const newScores = currentScores.concat(this.state.scoreInput);
    this.setState({ scores: newScores });
    

提交回复
热议问题