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
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
Share Improve this question asked Apr 27, 2018 at 5:34 Alexey KAlexey K 6,73319 gold badges65 silver badges122 bronze badges 4-
Shouldn’t that be
media:
instead ofmedia =
? – Sebastian Simon Commented Apr 27, 2018 at 5:39 - no, this way it removes all objects besides modified one – Alexey K Commented Apr 27, 2018 at 5:42
- what do you want to achieve? what is your actions payload looking like? – JanS Commented Apr 27, 2018 at 5:44
- What I need is to remove element in media array. – Alexey K Commented Apr 27, 2018 at 5:45
1 Answer
Reset to default 5What 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
. The only difference between line
and state
is that it's an array. 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
.
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/recipes/structuring-reducers/immutable-update-patterns
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744189837a4562381.html
评论列表(0条)