小编典典

为什么我不能在react.js的状态数组中推送值?

reactjs

我可以将1个项目添加到它在控制台中记录为 [“ 50”] 的阵列中。但是,当我尝试添加第二个值时,出现此错误“
currentScores.push不是函数 ”。这是错误的做法吗?

 class Scores extends 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.push(this.state.scoreInput);
        this.setState({ scores: newScores });
        console.log(this.state.scores);
      }

      handleScoreChange(e) {
        this.setState({ scoreInput: e.target.value });
      }

      render() {
        const scores = this.state.scores;
        return (
                <input name="score" type="text" placeholder="Score" onChange={this.handleScoreChange}/>
                <button onClick={this.addScore(this.state.scoreInput)}>add</button>
        );
      }
    }

    export default Scores;

阅读 255

收藏
2020-07-22

共1个答案

小编典典

两件事,当您使用push它时不会返回new array。利用concat并将值绑定到addUser函数。

另外,将元素包装在单个div中,并编写console.log()语句以在callbacksetState函数中输出状态值,因为这需要花费一些时间才能进行突变

 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 (

                <div>

                <input name="score" type="text" placeholder="Score" onChange={this.handleScoreChange}/>

                <button onClick={this.addScore.bind(this, this.state.scoreInput)}>add</button></div>

        );

      }

    }



    ReactDOM.render(<Scores/>, document.getElementById('app'));


<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>
2020-07-22