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

How can you unshift each element of the list with immutable js?

我想取消移动不可变列表中数组的每个元素

我的处决结果如下。 enter image description here

->列表[列表[new_element],元素,元素,元素]

我想要这个结果。

->列表[new_element,元素,元素,元素]

我该如何解决?


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')
        }
    }

从代码示例中的表达式 action.data.length 看来,您应该迭代 action.data 并将每个项目添加到 data

If action.data is an array or other iterable, fromJS(action.data) will return you a new List.


您可以使用 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);
}

或者更简单,使用 List::concat 方法。

请注意,上面的示例颠倒了 action.data 中的项目顺序,而下面的示例则没有。

此外,上面的示例确实将每个 item 转换为不可变的 ListMap(如果它是数组)。对象,而下面的例子没有。

if (action.listType === 'new') {
    return state
        .setIn(['memoList', 'status'], 'SUCCESS')
        .setIn(['memoList', 'data'], fromJS(action.data).concat(data));
}