简体   繁体   English

如何删除 Redux Reducer 中的嵌套数组元素?

[英]How to remove a nested array element in Redux Reducer?

been banging my head against this for hours.几个小时以来一直在努力解决这个问题。

I am trying to remove a nested elment of an array in an object.我正在尝试删除 object 中数组的嵌套元素。 It must be done immutably within a reducer, which is making it tricky.它必须在 reducer 中不可更改地完成,这很棘手。

Here is the object:这是 object:

questions {
    0:
    answers: [{…}]
    createdAt: "2021-04-28T01:37:21.017Z"
    creator: "607f6ab0ee09c"
    likes: []
    name: "Firstname Lastname"
}

I want to remove just 1 element of the answers array.我只想删除 answers 数组的 1 个元素。 The problem is I don't know the exact element (of questions) until I search by 'creator' code, and then I can delete the answers element by key #.问题是我不知道(问题的)确切元素,直到我通过“创建者”代码搜索,然后我可以通过键 # 删除答案元素。

I tried using map and filter, but with 3 layers deep that logic just never worked out.我尝试使用 map 和过滤器,但是在 3 层深的情况下,该逻辑从未奏效。 I'm also open to using Immutable-js.我也愿意使用 Immutable-js。

thanks so much, quite a baffling issue for what seems like a simple thing to do.非常感谢,对于看起来很简单的事情来说,这是一个令人费解的问题。

EDIT: I realized I can determine the key of the top level questions object in the action creator and send it over to the reducer.编辑:我意识到我可以在动作创建器中确定顶级问题 object 的关键并将其发送到减速器。 So all I need to know how to do is remove an element of an array in an object, nested in another object.所以我只需要知道如何删除嵌套在另一个 object 中的 object 中的数组元素。

thanks for any help!谢谢你的帮助!

First of clone your questions object by using ... ES6 operator首先使用... ES6 运算符克隆您的questions object

const clonedQuestion = {...questions}

Now for removing element from answers array现在从答案数组中删除元素

const indexOfElementToRemove = clonedQuestion.answers.findIndex(element => element.creator === clonedQuestion.creator);
if(indexOfElementToRemove >= 0) {
  clonedQuestion.answers.splice(indexOfElementToRemove, 1)
}

You might also take a look at the official redux toolkit, which would allow you to just use mutating logic like this in their createReducer - or createSlice - created reducers:你也可以看看官方的 redux 工具包,它允许你在他们的createReducer - 或createSlice - 创建的 reducer 中使用像这样的变异逻辑:

delete state.questions.answers[5]

See this tutorial page that gives a short overview over what we consider as "modern redux":https://redux.js.org/tutorials/fundamentals/part-8-modern-redux请参阅本教程页面,该页面简要概述了我们认为的“现代 redux”:https://redux.js.org/tutorials/fundamentals/part-8-modern-redux

If that is not something you want to do right now (keep in mind though, that modern redux and legacy redux can be mixed in an application), look into immer instead of immutable since immutable is essentially dead at this point and immer has a much better developer experience.如果这不是您现在想要做的事情(但请记住,现代 redux 和传统 redux 可以在应用程序中混合使用),请查看immer而不是immutable ,因为此时immutable基本上已经死了,而immer有很多更好的开发者体验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM