使用immutability-helper来合并数组

时间:2017-05-19 11:59:05

标签: arrays reactjs merge immutability

我从以下代码中收到以下错误:
错误:update():$ merge期望类型' object&#39 ;;未定义

我试图合并2个数组,而只更新原始数组中的项目中的某些值。例如,我想更新状态更新的属性,而不是成员数组属性。

我认为问题可能是在更新方法中使用索引,但这只是猜测。有任何想法吗?如果有更好的方法,我想知道。

const oldProjects = [
    {id: 1, members:[{name: 'Al'},{name: 'Joe'}], status: 'new', updated: '2017-05-19 12:00:00'},
];

const newProjects = [
    {id: 1, members:[], status: 'in-progress', updated: '2017-05-19 14:05:00'},
    {id: 2, members:[], status: 'new', updated: '2017-05-19 14:10:00'},
    {id: 3, members:[], status: 'completed', updated: '2017-05-19 14:15:00'},
];

let newState = oldProjects;

newProjects.forEach(np => {
    const index = oldProjects.findIndex(op => op.id === np.id);
    if (index === -1) {
        newState = update(newState, {$push: np});
    } else {
        newState = update(newState, {
            index: {$merge: { status: np.status, updated: np.updated }}
        });
    }
});

1 个答案:

答案 0 :(得分:3)

使用动态密钥时,您需要在[]中指定它。因此,请index[]包裹在index内,以便在索引等于index时访问对象,否则只会在newState中查找键newProjects.forEach(np => { const index = oldProjects.findIndex(op => op.id === np.id); if (index === -1) { newState = update(newState, {$push: np}); } else { newState = update(newState, { [index]: {$merge: { status: np.status, updated: np.updated }} }); } });

尝试

var example = document.getElementById('glcanvas');
var context = example.getContext('webgl');
var pixels = new Uint8Array(context.drawingBufferWidth * context.drawingBufferHeight * 4); 
var data = context.readPixels(445, 650, context.drawingBufferWidth, context.drawingBufferHeight, context.RGBA, context.UNSIGNED_BYTE, pixels);