簡體   English   中英

將看不見的邏輯添加到只讀 state redux - 反應

[英]add unseen logic to readonly state redux - react

我已經標准化的事件如下所示:

"entities":{
"events":{
 "123":{
   ... data
 }
 "124":{
   ...data
 }
}}

我在一個簡單的材料 ui 列表中顯示列表

現在,當單擊按鈕時,列表中的任何新項目現在都“看不見”並且不應自動選擇

我需要添加“看不見”:真/假。 到基本的標准化數據? 然后每次有新事件時發送更新? 所以它看起來像:

"entities":{
"events":{
 "123":{
   ... data
   unseen:false
 }
 "124":{
   ...data
   unseen: true
 }
}}

還是最好保留一個新的未見過事件列表? 我正在尋找一種更好的方法來處理它

在這種情況下,我需要更改只讀 state 嗎? 因為現在我只更新一個完整的 object

redux state:

export interface EventsEntities {
  events: {
    [id: string]: Event;
  };
}
export interface EventState {
  readonly entities: EventsEntities;
  selectedItem: string | null;
  readonly result: string[];
}

Redux state 中的每個值都假定為只讀,因此在這兩種情況下都不需要刪除它。

您可以使用 Redux 操作更改unseen的屬性,例如

{
  type: 'toggle-unseen-event',
  eventId: '123',
  unseen: true
}

並像這樣在減速器中處理它:

function eventsReducer(state, action) {
  switch(action.type) {
    ...
    case 'toggle-unseen-event':
      return {
        ...state,
        events: {
          ...state.events,
          [action.eventId]: {
            ...state.events[action.eventId],
            unseen: action.unseen
          }
        }
      }
    ...
  }
}

正如你所看到的,我們沒有改變事件對象,所以它可以是只讀的。


Redux state 的最佳設計取決於您要使用數據的方式和位置。

如果某些組件中您僅使用事件數據(但不是unseen ),那么最好將未見事件列表保存在 Redux state 中的單獨位置,以便更改unseen屬性不會導致重新渲染未顯示的組件不關心它。

但是,如果您在使用事件數據的任何地方都使用unseen屬性,那么最好將它們保存在同一個位置,這樣您就不需要每次都合並 unseen 列表和事件數據。

暫無
暫無

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

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