gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:53:16 27 4
gpt4 key购买 nike

我可以将 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 时,它不会返回新数组。使用 concat 并将值绑定(bind)到 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>

关于javascript - 为什么我不能在 react.js 中将值推送到我的状态数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41376203/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com