簡體   English   中英

使用“unshift”方法將項目添加到 Map Object 的開頭

[英]Add item to beginning of an Map Object with "unshift" method

  const { items, ids } = action.payload;
  const { fetchedItems } = state;
  const diff = _.difference(state.ids, action.payload.ids);
  // @APPEND
  for (let i = 0; i < items.length; i++) {
    fetchedItems.set(items[i].id, items[i]);
  }
  // @DELETE
  for (let i = 0; i < diff.length; i++) {
    fetchedItems.delete(diff[i]);
  }
  const myArray = Array.from(fetchedItems.values());
  return {
    ...state,
    items: Array.from(fetchedItems.values()), // not for use
    fetchedItems,
    ids: action.payload.ids,
    syncStatus: action.payload.tocMeta.syncStatus
  };

Quesstion is: my API based on sockets and every time i am receive new object, i am use Map object for ease update and delete and everything working nice, i want to set new items which coming from action.payload object on the first index of Map“像 unshift”,你能提供一些技巧嗎? 因為 new Map().Set() 將新項目放在 Map object 的底部,我不想每次都做 Map.clear()。

我不認為有什么好方法。 Map的順序由插入順序決定,因此,如果要先指定特定值,則唯一的選擇是先插入該值。

我也不確定在這種情況下使用Map是否真的是一個好主意。 在Redux中,您不應該像在for循環中那樣修改狀態(修改Map)。 這使得Maps在Redux中很難使用,因為在安全使用.set.delete類的方法之前,您需要不斷制作Map的副本。

Redux的創建者說過(關於Set和Map)

我認為在Redux中使用它們不是一個好主意,因為它們針對可變性進行了優化。 如果您想使用相似的語義獲得高效的東西,請考慮使用Immutable.js。

因此,我可能會改回使用具有便捷的非變異方法(如.map.filter (並適用於...語法)的數組),或者使用對象(將id作為鍵,並且可以使用ids跟蹤訂單)。

你有一個'fetchedItems'變量,它是一個Map(可能是一個狀態),你想把一個項目放在第一位......當你執行setState時,你可以用prevState替換'fetchedItem'

`

    const fetchedItemsArray = Array.from(fetchedItems.entries())

或更現代的方式:

    const fetchedItemsArray = [...fetchedItems.entries()]

那么你可以說:

    fetchedItems = new Map([

        [newValue.id, newValue], => firstItem

        ...fetchedItemsArray => spread all of the other items

     ])

或在這樣的 setState 操作中:

     setFetchedItems( prev => new Map([

                        [newValue.id, newValue],
                        ...Array.from(prev.entries())
                    ]));

` 我希望這會有所幫助,Map 構造函數接受 arrays 列表,其中第一項是鍵,第二項是值

暫無
暫無

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

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