简体   繁体   English

JS Spread运算符和嵌套数组

[英]Js spread operator and nested arrays

I have following object 我有以下对象

state = {"line": [
   {"media": [1, 2, 3 ]},
   {"media": []},
   {"media": []},
]}

What I need is to remove element in media array. 我需要删除媒体数组中的元素。

I try the following 我尝试以下

return {
            ...state, line: [{
                ...state.line[line_index], media = [
                        ...state.line[line_index].media.slice(0, action.payload.index),
                        ...state.line[line_index].media.slice(action.payload.index + 1)
                ]
            }]
        }

but it doesn't work, it replaces media with object. 但它不起作用,它用对象代替媒体。

I don't get how to do it correctly. 我不知道如何正确地做。 Can some one please show the way and describe it please 可以请一个人说明一下并描述一下吗

What you forgot is reassembling the line array properly. 您忘记的是正确地重新组装了线阵列。 Try breaking it down like this: 尝试像这样分解它:

const changedElement = {
    ...state.line[lineIndex],
    media: [
        ...state.line[lineIndex].media.slice(0, action.payload.index),
        ...state.line[line_index].media.slice(action.payload.index + 1)
    ]
}

return {
    ...state,
    line: [
        ...state.line.slice(0, line_index),
        changedElement,
        ...state.line.slice(line_index + 1)
    ]
}

What you want to do is write the current structure of your state: 您要做的是编写状态的当前结构:

state = {
    line: [
        {
            media: []
        },
        {
            media: []
        }
    ]
}

What you can then do is making it generic and containing state. 然后,您可以做的就是使其通用并包含状态。 So, state should be a copy of state (by putting ...state in it) and line should be a copy of line . 因此, state应该是一个拷贝state (通过把...state中的话)和line应该是一个拷贝line The only difference between line and state is that it's an array. linestate之间的唯一区别是它是一个数组。 Making an immutable copy of an array is a bit more involved than making such a copy of an object. 制作数组的不变副本比制作对象的副本要复杂得多。 But in your code, you did this already for your changedElement . 但是在您的代码中,您已经为changedElement完成了此changedElement

For a further read on this, you should have a look at immutable update patterns, as these are just recipes you can always reuse: https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns 有关此内容的进一步阅读,您应该看一下不可变的更新模式,因为这些只是您可以随时重复使用的配方: https : //redux.js.org/recipes/structuring-reducers/immutable-update-patterns

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

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