如何解决如何使用setState reactjs将对象推入数组中?
我在类组件中的状态
以下给出的状态在我的班级组件中。
我需要在starttime Array中添加以下示例动态对象。
this.state = {
frequency: {
starttime: [],},};
下面给出的示例对象。
{time:"20:15",timezone:"IST"},{time:"01:30",timezone:"UST"}
上述对象是我处理的动态对象。
我的要求是必须使用reactjs中的setState
将这些对象推送到starttime Array中。
预期结果如下。
this.state = {
frequency: {
starttime: [{time:"20:15",timezone:"UST"},{time:"13:00",...],};
解决方法
请考虑您是否将数据存储在名为newTimes
的变量中,该变量在状态下需要更新为starttime
。然后,下面是更新它的方法之一。您可以参考here了解有关更新时如何使用先前状态的更多详细信息。
let newTimes = [{time:"20:15",timezone:"IST"},{time:"01:30",timezone:"UST"}];
this.setState(state => ({
...state,frequency: {
starttime: [...state.frequency.starttime,...newTimes]
}
}))
如果您要根据条件从newTimes
数组中删除某些元素,那么Array.filter
将很方便。为简单起见,我考虑基于timezone
过滤数据,以下是示例
let newTimes = [{time:"20:15",timezone:"UST"},{time:"16:45",timezone:"GMT"}];
//Removing all the timezones which are of "UST".
//You can change this condition as per your requirement.
const filteredTimes = newTimes.filter(({ timezone }) => timezone !== "UST");
this.setState(state => ({
...state,...filteredTimes]
}
}))
从数组中删除重复项的方法有多种,请参考以下内容
let newTimes = [{time:"20:15",timezone:"GMT"},{time:"20:15",timezone:"PST"},{time:"12:30",timezone:"IST"}];
const removeDuplicates = (times) => {
const finalRes = times.reduce((res,timeObj) => {
const { time,timezone } = timeObj;
const key = `${time}_${timezone}`;
//Check if either the time or timezone are not same with any property from the result object.
//If either of them is not matching,then add it to the res object
if(res[key]?.time !== timeObj.time || res[key]?.timezone !== timeObj.timezone) {
res[key] = {...timeObj}
}
return res;
},{});
//Finally return the values of the object by converting it to an array.
return Object.values(finalRes);
}
console.log(removeDuplicates(newTimes))
.as-console-wrapper {
max-height: 100% !important;
}
- 使用
Array.filter
let newTimes = [{time:"20:15",timezone:"IST"}];
const removeDuplicates = (times) => {
let obj = {};
return times.filter(timeObj => {
const {time,timezone} = timeObj;
const key = `${time}_${timezone}`;
//Check if the formatted key is already present in the `obj`,if so return false else add the key and then return true.
return obj[key] ? false: (obj[key] = true,true)
});
}
console.log(removeDuplicates(newTimes))
.as-console-wrapper {
max-height: 100% !important;
}
,
只需使用传播算子将最后一个对象的状态与新的时代结合起来
请参见下面的示例:
let times = [];
times.push({time:"20:15",timezone:"UST"});
this.setState({
...this.state,// spread here to prevent removing other key object if present
frequency: {
starttime : [...this.state.frequency.starttime,...times] // merge previous value with new array
}
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。