我有一个按钮可以将内容添加到一些数组中。使用 .push 时,元素添加正确(因为它看起来像使用了 for 循环)但是当我第二次单击该按钮时,出现上述错误。这是我的一些代码:
class App extends Component {
constructor(props) {
super(props);
this.state = {
key: uuid(),
title: "",
author: "",
questions: [],
answers: []
};
this.handleChange = this.handleChange.bind(this);
}
//yada yada
addQuestion = () => {
questionNum++;
this.setState({
questions: this.state.questions.concat(["question", "hi"])
});
console.log(this.state.questions);
for (var i = 0; i < 4; i++) {
this.setState({
answers: this.state.answers.push({
answerChoice: "",
key: uuid()
})
});
}
console.log(this.state.answers);
console.log(questionNum);
console.log(this.state.title);
console.log(this.state.author);
};
render() {
//yada yada
<div>
<form>
<div className="Intro">
Give your Quiz a title:{" "}
<input
type="text"
value={this.state.title}
onChange={this.handleChange}
name="title"
/>
<br />
Who's the Author?{" "}
<input
type="text"
value={this.state.author}
onChange={this.handleChange}
name="author"
/>
<br />
<br />
</div>
<div className="questions">
Now let's add some questions... <br />
{this.addQuestion}
</div>
</form>
<button onClick={this.addQuestion}>Add Question</button>
</div>;
//yada yada
}
}
export default App;
但是当我更换
this.setState({
answers: this.state.answers.push({
answerChoice: '',
key: uuid()
})
})
与
this.setState({
answers: this.state.answers.concat({
answerChoice: '',
key: uuid()
})
})
似乎我的 for 循环不起作用(因为其中四个没有添加)。我对 React 和 JS 很陌生,所以任何提示都会有所帮助。
谢谢!
最佳答案
你不应该使用 push
,因为它会改变当前状态中的数组。
当您更新派生自当前状态的状态时,最好为 setState
提供一个函数并返回该函数的状态更改。否则存在覆盖状态更新的风险,这就是您的第二个示例中发生的情况。
您可以改为展开状态中的当前数组并向其中添加新对象。
this.setState(previousState => {
return {
answers: [...previousState.answers, { answerChoice: '', key: uuid() }]
};
});
如果您愿意,您还可以将状态更新组合在一起并仅使用一次 setState
:
addQuestion = () => {
questionNum++;
this.setState(previousState => {
const questions = [...previousState.questions, "question", "hi"];
const answers = [...previousState.answers];
for (var i = 0; i < 4; i++) {
answers.push({
answerChoice: "",
key: uuid()
});
}
return { questions, answers };
});
});
关于javascript - TypeError : _this. state.answers.push 不是函数 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51270552/