简体   繁体   English

如何使用不可变的js取消列表中的每个元素?

[英]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 new List . 如果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转换为不可变的ListMap如果它是数组的话。 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.

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