簡體   English   中英

如何使用setState reactjs將對象推送到數組內?

[英]How to push object inside the array using setState reactjs?

我在類組件中的狀態

下面給定的狀態在我的類組件中。

我需要在 starttime 數組中添加以下示例動態對象。

this.state = {
   frequency: {
       starttime: [],
   },
};

下面給出的示例對象。

{time:"20:15",timezone:"IST"},
{time:"01:30",timezone:"UST"}

上面的對象是我動態處理的。

我的要求是必須使用 reactjs 中的setState將這些對象推送到 starttime 數組中。

預期結果如下。

this.state = {
   frequency: {
      starttime: [{time:"20:15",timezone:"IST"},
         {time:"01:30",timezone:"UST"},
         {time:"13:00",timezone:"UST"},...],
      },
};

考慮你有一個變量稱為數據newTimes需要進行更新starttime的狀態。 那么下面是您可以更新它的方法之一。 您可以在此處參考有關更新時如何使用先前狀態的更多詳細信息。

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:"IST"}, {time:"01:30",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,
  frequency: {
    starttime: [...state.frequency.starttime, ...filteredTimes]
  }
}))

從數組中刪除重復項的方法有多種,請參閱下文

 let newTimes = [{time:"20:15",timezone:"IST"}, {time:"01:30",timezone:"UST"}, {time:"16:45",timezone:"GMT"}, {time:"20:15",timezone:"IST"},{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"}, {time:"01:30",timezone:"UST"}, {time:"16:45",timezone:"GMT"}, {time:"20:15",timezone:"IST"},{time:"20:15",timezone:"PST"},{time:"12:30",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:"IST"},{time:"01:30",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
   }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM