首页 > 解决方案 > 使用不变性助手`update`时如何使用我的索引作为键

问题描述

我正在尝试使用react 文档中建议的immutability-helper更新我的列表,您可以看到我当前用于更新的代码

    const oldInstallment = this.findInstallmentByIndex(this.state.installmentList, index);
    let newInstallment =  {...oldInstallment}
    newInstallment.isActivated = isActivated;

    const newInstallmentList = update(this.state.installmentList, {index: {$set: newInstallment}});
    this.setState({installmentList: newInstallmentList});

我目前遇到的问题是,index它没有用作值,而是用作键,命名index含义而不是说明0:{$set: newInstallment}代码的作用是index:{$set: newInstallment}导致向数组中添加新元素而不是更新元素index 0
所以我的问题是如何我告诉这个更新方法使用我的索引值作为键?!

标签: reactjsimmutability

解决方案


试着这样写:

const newInstallmentList = update(this.state.installmentList, {[index]: {$set: newInstallment}});

推荐阅读