删除减速器中的动态属性

Mih*_*anu 2 javascript reactjs redux

我想将我想与有效负载一起删除的条目的 id 动态传递到减速器中,并且我正在尝试删除一个对象属性(具有“eowvw698x”id 的那个是动态的并且可能会改变)并保留现有的.

case DELETE_ENTRY:
   return {
     ...state,
     diaryEntries: {
       ...state.diaryEntries,
       ??????
     },
   };
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我怎样才能做到这一点?

编辑

我使用了 Vencovsky 的回答和 Klaycon 的评论建议并写道:

case DELETE_ENTRY:
  const { [payload]: dontcare, ...otherProperties } = state.diaryEntries;
  return {
    ...state,
    diaryEntries: {
      ...otherProperties,
    },
  };
Run Code Online (Sandbox Code Playgroud)

其他人的解决方案使状态对象发生变异,这是最高算法所禁止的。

Ven*_*sky 5

您可以通过销毁state.diaryEntries来删除该 ID

   const { eowvw698x, ...otherProperties } = state.diaryEntries

   return {
     ...state,
     diaryEntries: {
       ...otherProperties 
     },
   };
Run Code Online (Sandbox Code Playgroud)

或者

这不是最好的方法,但您可以将其设置为undefined.

   return {
     ...state,
     diaryEntries: {
       ...state.diaryEntries,
       eowvw698x: undefined 
     },
   };
Run Code Online (Sandbox Code Playgroud)

编辑

正如评论中所说,您正在寻找的是动态销毁变量,您可以在此问题中了解如何执行此操作。

但是对于您的示例,您可以做的是破坏并命名变量,只是将其删除。

   const { [keyToRemove]: anyVariableNameYouWontUse, ...otherProperties } = state.diaryEntries

   return {
     ...state,
     diaryEntries: {
       ...otherProperties 
     },
   };
Run Code Online (Sandbox Code Playgroud)

  • @MihaiCiobanu 请相应地更新您的问题,这是一个重要的细节。 (4认同)
  • @MihaiCiobanu这可以通过别名来完成: `{ [payload]: dontcare, ...otherProperties } = state.diaryEntries` 会将键为 `payload` 值的属性存储到 `dontcare` 和其余属性中在“其他属性”中 (4认同)