0

在使用 redux 的本机应用程序中,我想使用 immutable-js 更新应用程序的状态。我mergeDeep用来更新状态。有一个问题:当从数组中删除一个元素时。所以我通过将新数据转换为不可变数据然后比较大小来检测这种情况。这工作正常:

function updateSettings(state, action) {
    const mutablePath = [].concat(action.path);
    const lastPathKey = mutablePath.pop();
    let nextState;
    let newArr;

    if (isInt(lastPathKey)) {
        // An array has been changed
        if (Immutable.fromJS(action.data).getIn(mutablePath).size < state.getIn(mutablePath).size) {
            // The element at lastPathKey has been removed
            newArr = state.getIn(mutablePath).remove(lastPathKey);
            nextState = state.setIn(mutablePath, newArr);
        }
    }

    if (!nextState) {
        nextState = state.mergeDeep(action.data);
    }

    return nextState;
}

action.data 始终是完整的对象路径(因为我使用的是 tcomb-form-native):如果元素已更改,则操作路径如下所示:

action.path = ["testStruct", "deepArray", 0, "objectArr", "valDAOA1"]
action.data = {
    "isShowHelp": false,
    "testStruct": {
        "deepArray: [
            {
                "objectArr": {
                    "valDAOA1": 10
                }
            },
            {
                "objectArr": {
                    "valDAOA1": 20
                }
            }
        ]
    }
}

如果数组元素已被删除:

action.path = ["testStruct", "deepArray", 1]
action.data = {
    "isShowHelp": false,
    "testStruct": {
        "deepArray: [
            {
                "objectArr": {
                    "valDAOA1": 10
                }
            }
        ]
    }
}

我想知道使用https://stackoverflow.com/a/6491621/4025963中提出的手动方法获取数组大小是否更有效,以及是否应该考虑其他情况。

4

0 回答 0