如何在React中更新深层嵌套状态

问题描述 投票:0回答:1
[
{  
year:2022, 
month:"jan",
days: [
            { day: 1, isCompleted: false },
            { day: 2, isCompleted: false },
            // ... other days
      ]
},
{  
year:2022, 
month:"feb",
days: [
            { day: 1, isCompleted: false },
            { day: 2, isCompleted: false },
            // ... other days
      ]
},
// ... other months
]

我的状态值就是这样。我渲染所有日子,如果我单击特定日期,我想将其 isCompleted 属性更新为 true。我该如何更新。

我不知道如何更新嵌套状态

reactjs date nested state
1个回答
0
投票

您需要查找年、月、日。然后只需将

isCompleted
值设置为
true
。这可能有点复杂,因为设置状态时你不能修改状态本身。

const SomeComponent = () => {
  const [datesState, setDatesState] = useState([...]);

  const onSelectDate = (inputDate) => {
    const inputDateDay = inputDate.getDate();
    const inputDateMonth = inputDate.toLocaleString("en-US", { month: "short" }).toLowerCase();
    const inputDateYear = inputDate.getFullYear();

    setDatesState((prev) => {
      const matchingYearAndMonthIndex = datesState.findIndex((date) => date.year === inputDateYear && date.month === inputDateMonth);

      if (matchingYearAndMonthIndex === -1) {
        return prev;
      }

      const matchingDayIndex = prev[matchingYearAndMonthIndex].findIndex((date) => date.day === inputDateDay);

      if (matchingDayIndex === -1) {
        return prev;
      }

      const prevCopy = [...prev];
      const yearAndMonthCopy = { ...prev[matchingYearAndMonthIndex] };
      const daysCopy = [ ...yearAndMonthCopy.days ];

      daysCopy[matchingDayIndex].isCompleted = true;
      yearAndMonthCopy.days = daysCopy;
      prevCopy[matchingYearAndMonthIndex] = yearAndMonthCopy;

      return prevCopy;
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.