React Native 如何从数组中筛选出对象,然后使用开关切换将其重新添加回来

ycl3bljg  于 2023-05-07  发布在  React
关注(0)|答案(2)|浏览(103)

我的数组

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"}]

如果我再次打开它,数组再次为空:

[]

它继续执行以下行为:再次添加“Sunday”对象,然后为空,然后在每次切换时添加“Sunday”。
我想实现的是这个场景:

我知道错误在filter()内部的某个地方,我只是看起来无法弄清楚。
它是否与实际的filter()以及它的过滤条件item => item.day !== business_hours[0].day.includes()有关?
谢谢你的帮助,我是一个初学者,当涉及到数组操作。

rdrgkggo

rdrgkggo1#

你需要把你的代码改成这个

const updatedBusinessHours = business_hours.filter(item => item.day !== "Sunday")

在你的代码里

const updatedBusinessHours = business_hours.filter(item => item.day !== business_hours[0].day)

你在上面这行做的是过滤掉第一个对象。不管是星期天还是星期一。business_hours[0]选择数组中的第一个对象。它不检查是星期天还是星期一或其他时间。

sirbozc5

sirbozc52#

你可以使用下面给出的东西。

const updateList = (dayName) => {
    const arrayList = [
      {close_time: 'Not set', day: 'Sunday', open_time: 'Not set'},
    ];
    const exist = arrayList.findIndex(item => item.day === dayName);
    if (exist > -1) {
      //record exist remove
      arrayList.splice(exist, 1);
    } else {
      //not exist add
      arrayList.push({
        close_time: 'Not set',
        day: dayName,
        open_time: 'Not set',
      });
    }
  };

相关问题