reactjs - 使用 setState 方法更新嵌套对象格式的状态数据
问题描述
class TreeStructure extends Component {
constructor(props) {
super(props);
this.state = {
componentData: {},
modalIsOpen: false,
}
this.cleanObject = this.center code hereleanObject.bind(this);
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.update = this.update.bind(this);
}
componentDidMount() {
this.setState({
componentData: this.props.componentData
})
}
componentWillReceiveProps(nextProps){
this.setState({
componentData: nextProps.componentData
})
}
openModal(){
this.setState({
modalIsOpen: true,
})
}
closeModal(){
this.setState({
modalIsOpen: false,
})
}
update(key, subKey, k, values){
// this.setState({
// modalIsOpen: true,
// })
console.log("key: " + key)
}
cleanObject(obj1){
const obj = Object.assign({}, obj1);
delete obj.__v;
delete obj._id;
delete obj.name;
return obj;
}
render() {
return(
<div>
<Modal
isOpen={this.state.modalIsOpen}
onRequestClose={this.closeModal}
contentLabel="Add Expense"
className="Modal">
<form>
<input type="text"/>:
<input type="text"/>
</form>
</Modal>
{Object.keys(this.state.componentData).map((key, i) => {
return (
<TreeView
key={i}
nodeLabel={key}
// defaultCollapsed={true}
> <button>Add Row</button>
{Object.keys(this.state.componentData[key]).map((subKey, j) => {
return (
<TreeView
key={j}
nodeLabel={subKey}
// defaultCollapsed={true}
> <button>Add Row</button>
{this.state.componentData[key][subKey].map((superSubComponent, k) => {
<div>{superSubComponent = this.cleanObject(superSubComponent)}</div>
return(
<TreeView
key={k}
nodeLabel={k}
// defaultCollapsed={true}
> <button>Add Key and Value</button>
{Object.keys(superSubComponent).map((values, l) => {
return (
// <div key={l}>{values}: {superSubComponent[values]}<button onClick={this.update}>Edit</button><button>Delete</button></div>
<div key={l}>
<div className="key">{values}: </div>
<div className="value">{superSubComponent[values]}</div>
<button onClick={this.update(key, subKey, k, values)}>Edit</button><button>Delete</button>
</div>
)
})}
</TreeView>
)
})}
</TreeView>
)
})}
</TreeView>
)
})}
</div>
);
}
}
我想componentData
用this.update
. 有人可以给我一些建议吗?我尝试更新状态,update()
但我得到maximum update depth exceeded
. componentData
我的主要目标是更新TreeStructure
组件,然后用它来更新 mongo 数据库。由于架构不固定,我认为替换数据库中的整个文档可能是最好的选择。所以我需要 compoentData
作为文件。
解决方案
问题在这里:
onClick={this.update(key, subKey, k, values)}
你在渲染时调用它,调用更新状态,触发重新渲染,再次执行该调用,依此类推。给onClick
一个函数:
onClick={() => this.update(key, subKey, k, values)}
推荐阅读
- html - Flexbox:Firefox、Chrome 和 Safari
- mysql - 将 AWS RDS 迁移到 GCP (sql 5.7)
- minecraft - Spigot 1.17 播放器控制台事件
- module - lua setmetatable - 错误 = 尝试调用全局“setmetatable”(一个 nil 值)
- powershell - 脚本擦除软件的问题
- node.js - 如何通过重写设置 Nginx 反向代理?
- python - 在 selenium python 中通过文本查找后定位元素
- mysql - 是否可以在闪亮的管理器上使用 MySQL 而不是 SQLite?
- linux - 如何知道 Linux Split 中拆分后的文件总数
- java - 基于技能的总价值未正确打印