I want to unshift each element of an array in immutable list
My execution resulted in the following. enter image description here
-> List[List[new_element], element, element, element]
I want this result.
-> List[new_element, element, element, element]
How can i fix it?
case types.MEMO_LIST_SUCCESS:
if (action.listType === 'new') {
if(action.data.length !== 0) {
return state.setIn(['memoList', 'status'], 'SUCCESS')
.setIn(['memoList', 'data'], data.unshift(fromJS(action.data)));
} else {
return state.setIn(['memoList', 'status'], 'SUCCESS')
}
}
From the expression action.data.length
in your code example it looks like you should iterate action.data
and add each item to data
.
If
action.data
is an array or other iterable,fromJS(action.data)
will return you a newList
.
You could use Array.prototype.reduce
and pass data
as initial value for the accumulation, adding to it by iterating action.data
:
if (action.listType === 'new') {
const newData = action.data.reduce((acc, item) => acc.unshift(fromJs(item)), data);
return state
.setIn(['memoList', 'status'], 'SUCCESS')
.setIn(['memoList', 'data'], newData);
}
Or even easier, use the List::concat
method.
Note that the above example reverses the order of items in of action.data
, whereas the following example does not.
Also the example above does convert each item
to immutable List
or Map
if it is an array resp. object, whereas the following example does not.
if (action.listType === 'new') {
return state
.setIn(['memoList', 'status'], 'SUCCESS')
.setIn(['memoList', 'data'], fromJS(action.data).concat(data));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.