javascript - 删除 reducer 中的动态属性

标签 javascript reactjs redux

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

case DELETE_ENTRY:
   return {
     ...state,
     diaryEntries: {
       ...state.diaryEntries,
       ??????
     },
   };

enter image description here

我怎样才能实现这个目标?

编辑

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

case DELETE_ENTRY:
  const { [payload]: dontcare, ...otherProperties } = state.diaryEntries;
  return {
    ...state,
    diaryEntries: {
      ...otherProperties,
    },
  };

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

最佳答案

您可以破坏state.diaryEntries来删除该id

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

   return {
     ...state,
     diaryEntries: {
       ...otherProperties 
     },
   };

或者

这不是最好的方法,但您可以将其设置为未定义

   return {
     ...state,
     diaryEntries: {
       ...state.diaryEntries,
       eowvw698x: undefined 
     },
   };

编辑

正如评论中所说,您正在寻找的是动态破坏变量,您可以在 this question 中了解如何执行此操作。 .

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

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

   return {
     ...state,
     diaryEntries: {
       ...otherProperties 
     },
   };

关于javascript - 删除 reducer 中的动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59460653/

相关文章:

javascript - 防止用户多次选择测验选项

javascript - 如何在html文本输入中只允许输入冒号分隔的2位数字?

javascript - this.context 在使用 react-router 时不包含 router

javascript - react : How to clear form only after SUCCESSFUL submit?

javascript - Angular js - 有条件地打印 View 数据

javascript - 使用 Selenium 测试 jQuery 元素数据()?

javascript - 如何挂接套件 :start/end with Buster. js?

reactjs - IIS 8.5 重写规则子目录和 ReactJs

javascript - 出现错误 TypeError : Cannot read property 'id' of undefined using React/Redux action

javascript - 尝试在 react 中添加多张图片,但它只显示一张图片