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

前端 未结 5 940
后悔当初
后悔当初 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:21

    The problem is that push doesn't return a new array, bit the length of the amended array. So you're actually assigning state.stores to a number, which of course doesn't support push.

    I can see you're trying to avoid mutating state by attempting to clone the scores array, but push will mutate it, not return a new instance. It might be better to do something like:

    const newScores = [...this.state.scores, this.state.scoreInput];
    this.setState({ scores: newScores });
    

提交回复
热议问题