[英]How can you unshift each element of the list with immutable js?
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] ->列表[列表[new_element],元素,元素,元素]
I want this result. 我想要这个结果。
-> List[new_element, element, element, element] ->列表[new_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
. 在代码示例中,从表达式
action.data.length
看来,您应该迭代action.data
并将每个项目添加到data
。
If
action.data
is an array or other iterable,fromJS(action.data)
will return you a newList
.如果
action.data
是数组或其他可迭代的,fromJS(action.data)
将为您返回一个新的List
。
You could use Array.prototype.reduce
and pass data
as initial value for the accumulation, adding to it by iterating action.data
: 您可以使用
Array.prototype.reduce
并将data
作为累积的初始值传递,并通过迭代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. 甚至更简单,使用
List::concat
方法。
Note that the above example reverses the order of items in of action.data
, whereas the following example does not. 请注意,上面的示例颠倒了
action.data
中项目的顺序,而下面的示例则没有。
Also the example above does convert each item
to immutable List
or Map
if it is an array resp. 同样,上面的示例确实将每个
item
转换为不可变的List
或Map
如果它是数组的话。 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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.