如何从两个数组中删除数据?
How can I delete data from two arrays?
我有一个显示时间列表的网格(不时)
例如
timeList=[{from:12:00:00 , to:14:00:00 ,id:10}{from:08:00:00 , to:09:00:00 ,id:11{from:05:00:00 , to:10:00:00 ,id:12}}]
time=[{Value:12:00:00 id:10}
{Value:14:00:00 id:100}
{Value:08:00:00 id:11}
{Value:09:00:00 id:110}
{Value:05:00:00 id:12}
{Value:10:00:00 id:15}
]
删除项目我有这个代码
deleteTimeView(data) {
////date ==>{from:12:00:00 , to:14:00:00 ,id:10}
let indexOfDeleted = -1;
let time = this.state.time;
let timeList=this.state.timeList;
this.state.time.forEach((item, index) => {
if (item.Id === data.id) {
indexOfDeleted = index;
}
})
time.splice(indexOfDeleted, 1);
time.splice(indexOfDeleted, 1);
timeList.splice(indexOfDeleted, 1);
this.setState({
time: time,
timeList: timeList
});
}
我的问题是,当我想删除id12时,我有索引4,但我在timeList中没有这个索引。
我及时删除该项目没有问题,但我怎样才能从 timeList 中删除它
首先,不要使用 .splice
,它会改变数组,在这种情况下意味着您直接改变状态。永远不要改变 React 中的状态。
其次,简单的基于ID的过滤方式应该能满足你的需求:
deleteTimeView(data) {
this.setState({
time: this.state.time.filter(t => t.id !== data.id),
timeList: this.state.timeList.filter(t => t.id !== data.id)
});
}
我有一个显示时间列表的网格(不时)
例如
timeList=[{from:12:00:00 , to:14:00:00 ,id:10}{from:08:00:00 , to:09:00:00 ,id:11{from:05:00:00 , to:10:00:00 ,id:12}}]
time=[{Value:12:00:00 id:10}
{Value:14:00:00 id:100}
{Value:08:00:00 id:11}
{Value:09:00:00 id:110}
{Value:05:00:00 id:12}
{Value:10:00:00 id:15}
]
删除项目我有这个代码
deleteTimeView(data) {
////date ==>{from:12:00:00 , to:14:00:00 ,id:10}
let indexOfDeleted = -1;
let time = this.state.time;
let timeList=this.state.timeList;
this.state.time.forEach((item, index) => {
if (item.Id === data.id) {
indexOfDeleted = index;
}
})
time.splice(indexOfDeleted, 1);
time.splice(indexOfDeleted, 1);
timeList.splice(indexOfDeleted, 1);
this.setState({
time: time,
timeList: timeList
});
}
我的问题是,当我想删除id12时,我有索引4,但我在timeList中没有这个索引。 我及时删除该项目没有问题,但我怎样才能从 timeList 中删除它
首先,不要使用 .splice
,它会改变数组,在这种情况下意味着您直接改变状态。永远不要改变 React 中的状态。
其次,简单的基于ID的过滤方式应该能满足你的需求:
deleteTimeView(data) {
this.setState({
time: this.state.time.filter(t => t.id !== data.id),
timeList: this.state.timeList.filter(t => t.id !== data.id)
});
}