arrays - 在反应状态下更改嵌套数组对象
问题描述
我想替换嵌套数组对象的值,如下所示,当单击按钮时,它将替换 x 索引对象的旧值并在那里设置新值。
class compo extends React.Component {
constructor() {
super();
this.state = {
tabsData:[
{
id:1,
title:"OldTitle1"
},
{
id:2,
title:"OldTitle2"
}
],
}
this.changeTab = this.changeTab.bind(this)
}
changeTab(){
const newData={
id=3,
title="New One"
}
//replace the above new data in the second object of nested array in state
}
render(){
return(
<button type="button" >Add</button>
)
;}
}
export default compo
之后的状态应该是这样的
tabsData:[
{
id:1,
title:"OldTitle"
},
{
id:3,
title:"New One"
}
]
解决方案
你可以做这样的事情......
import React from "react";
class compo extends React.Component {
constructor() {
super();
this.state = {
tabsData: [
{
id: 1,
title: "OldTitle1"
},
{
id: 2,
title: "OldTitle2"
}
]
};
this.changeTab = this.changeTab.bind(this);
}
changeTab() {
const newData = {
id: 3,
title: "New One"
};
// Make duplicate since you can't mutatue state
let newTabData = [...this.state.tabsData];
const id = 2; // id to be removed
// CASE 1: If you want to maintain order
const index = newTabData.findIndex((data) => data.id === id);
if (index > -1) {
// replace oldData with newData
newTabData.splice(index, 1, newData);
} else {
// simply add newData at last
newTabData.push(newData);
}
// CASE 2: If order doesn't matter
// // remove oldData
// newTabData = newTabData.filter((data) => data.id !== id);
// // add new data at last
// newTabData.push(newData);
// finally update the state irrespective of any case
this.setState({ tabsData: newTabData });
}
render() {
return (
<div>
<button type="button">
Add
</button>
<button type="button" onClick={this.changeTab}>
Change
</button>
<br />
{JSON.stringify(this.state, null, 2)}
</div>
);
}
}
export default compo;
推荐阅读
- ios - 为什么日期格式化程序崩溃?
- rest - 问题 AVR 卡住并且程序计数器丢失...?
- ipfs - IPFS 上是否可以进行临时、非持久存储?
- php - Prestashop 在管理面板侧边栏菜单中添加新项目
- php - 谷歌分析 API 错误的用户编号和维度
- python - Pandas 深拷贝和 scikit 学习 min max scaler
- python - 我可以缩短在 Python 中添加多个变量的过程吗?
- python - 正则表达式查找开始和结束之间的所有行
- node.js - Shopify Script Tags Create 方法未在控制台中显示响应
- c - errno == ENOENT 是否足以检查文件是否存在于 C 中?