javascript - 在 reactjs 中更新嵌套状态
问题描述
我有这个嵌套的状态,我很难设置状态。错误:未定义不是对象(评估 this.state.form) 我的初始状态是:
this.state={
activePage:0,
visible:false,
questionType:null,
form:{
title:'',
description:'',
pages:[{
title:'',
description:'',
questions:[
]
}]
}
};
现在每次用户点击时,我都需要向 pages 数组添加更多对象,这些对象应该有标题 ( ''
)、描述 ( ''
) 和问题(空列表)。我试图实现这一点,但它似乎并没有奏效。
let newForm={
...this.state,
form:{
...this.state.form,
pages:[
...this.state.form.pages,
pageData
]
}
};
console.log('newForm',newForm);
this.setState({
form:newForm
});
这就是我的 pageData 的样子
let pageData={
title:'',
description:'',
questions:[]
};
解决方案
您将整个设置state
在newForm
. 只需将其限制为form
对象:
let newForm = {
...this.state.form,
pages: [
...this.state.form.pages,
pageData
]
};
console.log('newForm', newForm);
this.setState({
form: newForm
});
推荐阅读
- php - 如何在 PHP 准备语句中将数据插入数组?
- spring - Spring BOOT Logger Actuator 在集群环境中的行为如何?
- hyperledger-fabric - 链码应该只安装在背书节点上吗?
- ruby-on-rails - 使用 Rails 进行日志配置
- javascript - 节点函数在循环中同步
- ios - 我需要在这部分中添加更多图像 cell.topCellImg.image = UIImage(named:"Image") 可以帮助我
- linux - 在脚本中使用 sed
- java - 如何对巨大的arrayList进行排序
(大约 2000 条记录)? - go - 如何获取 db2cmd 运行的 DB2 命令的输出?
- python - Bokek 悬停工具显示不正确 | Python