【问题标题】:Redux reducer failing to remove array elementRedux reducer 无法删除数组元素
【发布时间】:2017-03-10 17:32:13
【问题描述】:

我在尝试让 reducer 在 Redux 中正常工作时遇到问题。我是 Redux 的新手,所以我可能会遗漏一些简单的东西,但我已经玩了一段时间了,不知道出了什么问题。

这是我的过程:

定义参数:

首先我定义我需要的索引值。登录后,这将返回正确的数字...

const thisCommentIndex = parseInt(comments.indexOf(comment))

函数调用:

<div onClick={this.props.removeComment.bind(null, thisCommentIndex)}></div>

行动:

export function removeComment(index) {
   return {
      type: 'REMOVE_COMMENT',
      index
   }
}

减速机:

function comments(state = [], action) {
   switch(action.type) {
      case 'REMOVE_COMMENT' :
         console.log('removing comment with index of ' + action.index)
         return [
            ...state.slice(0, action.index), // why isn't this working???
            ...state.slice(action.index)
         ]
      default :
         return state
   }
   return state;
}

当我console.log('removing COMMENT with index of ' + action.index) 时,它会正确记录 action.index,这是我期望的整数。但该函数并未按预期删除元素。

奇怪的是,如果我只是传递数组索引,它可以正常工作(删除数组元素)。(我会这样做,但由于我设置应用程序的方式在这种情况下不起作用)。

我在这里遗漏了什么吗?任何帮助表示赞赏。

【问题讨论】:

  • 尝试用括号括住state.slice,以确保它不会先进行分解

标签: javascript arrays reactjs redux reducers


【解决方案1】:

您缺少+1...

return [
  ...state.slice(0, action.index),
  ...state.slice(action.index + 1) // <--- need to actually skip what you want to remove
]

【讨论】:

  • 天哪。我怎么错过了。我实际上之前有它工作过,但显然在没有意识到的情况下改变了那部分......感谢您指出! :)
【解决方案2】:

@Jack 是正确的。另一种选择是改用Array.filter

return state.filter( (item, index) => index !== action.index)

您可能对 Redux 文档的新 Structuring Reducers 部分感兴趣。特别是Immutable Update Patterns的页面有一些相关的例子。

【讨论】:

    【解决方案3】:

    如果你想删除多个项目,那么你可以向后处理你的数组

     for (var i = this.props.items.length -1; i >= 0; --i) {
       if(this.props.items[i]["selected"]) {
         this.props.deleteSelectedItem(i);
       }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 2018-02-27
      • 2018-07-02
      • 2014-10-16
      • 2018-08-29
      相关资源
      最近更新 更多