javascript - 道具传递的方法的 setState 上的无限循环
问题描述
我在从各种嵌套子组件传递给父组件的道具设置状态时遇到问题,这会导致应用程序由于 this.setState() 的无限循环而崩溃
这是最里面的子组件
SingleChoice.jsx
class SingleChoice extends Component {
state = {
choices: [{ name: "" }],
questionName: "",
type: "singleChoice"
};
componentDidUpdate() {
this.props.updateState(this.state);
}
}
由 AddQuestionOptions 调用
AddQuestionOptions.jsx
class AddQuestionOptions extends Component {
updateState = state => {
this.props.updateState(state);
};
render(){
<SingleChoice updateState={this.updateState} />
}
}
然后由 QuestionOptions 调用
QuestionOptions.jsx
class QuestionOptions extends Component {
state = {
value: 0,
questions: [{ name: "" }]
};
{...}
updateState = state => {
this.props.updateQuestion(state);
};
render(){
return(
<AddQuestionOptions
updateState={this.updateState}
/>
)
}
}
然后在父组件中调用方法...
SurveyForm.jsx
class SurveyForm extends Component {
state={
...,
questions: []
}
updateQuestion = state => {
const newQuestions = this.state.questions.map((question, idx) => {
if (idx !== this.state.questions.length - 1) return question;
return { ...question, state };
});
this.setState({
questions: newQuestions
});
};
render(){
return(
<QuestionOptions
updateQuestion={this.updateQuestion}
)
}
}
解决方案
推荐阅读
- c - 将双指针释放到结构的正确方法
- debugging - 如何在 GDB 中让 Firefox 启动更快
- bootstrap-4 - 有谁知道为什么引导程序中的自定义 Ajax 表不起作用?
- php - 重新加载页面时新的 sessionid 但转到另一个页面并再次返回时相同的 sessionid(不工作)
- c# - 为什么 System.Net.Http.Headers.HttpResponseHeaders 不可索引?
- arduino - Arduino 代码/存储空间不足/arduino uno
- javascript - 如何使用链接而不是按钮打开模式弹出窗口
- django - Django 上下文 Datetime 唯一日期
- php - 我的表单有可变数量的字段。如何使用 PHP 将每个字段提交到 MySQL 数据库?
- github - GitHub Actions (Workflows) 错误 - 计费问题