繁体   English   中英

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

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

我可以将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;

问题在于, push不会返回新数组,而是返回修改后的数组的长度 因此,您实际上是将state.stores分配给一个数字,这当然不支持push

我可以看到您正在尝试通过尝试克隆scores数组来避免状态发生变化,但是push将对其进行更改,而不返回新实例。 最好执行以下操作:

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

Push返回调用该方法的对象的新length属性。

每次将分数状态设置为新的长度。

addScore() {
        console.log(this.state.scores);
        this.setState(state=> ({
            scores: [...state.scores, state.scoreInput]
            })
         );
      }

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

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

  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> 

currentScores.push()的返回值是数组中元素的新数量。 然后,将其保存在您的状态中,这意味着您所在状态中的分数变为数字而不是数组。

您可能要构造一个新数组,因为您正在使用常量变量:

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

问题在这里<button onClick={this.addScore(this.state.scoreInput)}> add</button>);

当您在onclick中运行this.addScore(this.state.scoreInput)时,javascript运行时将调用addScore函数。 那就是为什么你得到50个日志

尝试<button onClick={ function(){this.addScore(this.state.scoreInput)}}> add</button>);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM