我的阵列
const initial_business_hours = [
{ "day": "Sunday", "open_time": "Not set", "close_time": "Not set" },
{ "day": "Monday", "open_time": "Not set", "close_time": "Not set" }
]
保存状态
const [business_hours, setBusinessHours] = useState(initial_business_hours);
开关切换状态
const [isSundaySwitchOn, setIsSundaySwitchOn] = useState(true);
从数组中删除/过滤对象的逻辑
const onToggleSundaySwitch = () => {
setIsSundaySwitchOn(!isSundaySwitchOn)
if (JSON.stringify(business_hours).includes(JSON.stringify({ "day": "Sunday", "open_time": "Not set", "close_time": "Not set" }))) {
const updatedBusinessHours = business_hours.filter(item => item.day !== business_hours[0].day)
return setBusinessHours(updatedBusinessHours)
}
setBusinessHours([...business_hours, { "day": "Sunday", "open_time": "Not set", "close_time": "Not set" }])
};
发生了什么
初始开关状态为真/开。发生的事情是,当我关闭开关时,它会删除所需的对象
{ "day": "Sunday", "open_time": "Not set", "close_time": "Not set" }
。到目前为止还可以。
当前数组状态:
[{"close_time": "Not set", "day": "Monday", "open_time": "Not set"}]
如果我打开开关,它会再次添加
{ "day": "Sunday", "open_time": "Not set", "close_time": "Not set" }
。这又是一种理想的行为。
当前数组状态:
[{"close_time": "Not set", "day": "Monday", "open_time": "Not set"},
{"close_time": "Not set", "day": "Sunday", "open_time": "Not set"}]
但是在下一次关闭时,删除的是现在
{ "day": "Monday", "open_time": "Not set", "close_time": "Not set" }
当前数组状态:
[{"close_time": "Not set", "day": "Sunday", "open_time": "Not set"}]
在下一次切换时,数组现在是空的。
[]
如果我再次关闭它,数组现在是:
[{"close_time": "Not set", "day": "Sunday", "open_time": "Not set"}]
如果我再次打开它,数组又是空的:
[]
它继续添加“星期日”对象的行为,然后清空,然后在每次切换时添加“星期日”。
我想要实现的是针对这种情况:
我知道错误在
filter()
的某个地方,我似乎无法弄清楚。
和实际的
filter()
和它的过滤条件item => item.day !== business_hours[0].day
和.includes()
有关系吗?
感谢您的帮助,我是数组操作的初学者。