将数组索引值更新为对象

时间:2021-04-12 14:24:37

I want to update the value of a key in an array with the immutability-helper addon.

我想用immutability-helper插件更新数组中键的值。

my code looks like this:

我的代码看起来像这样:

class StorageForm extends Component {
  constructor(props) {
    super(props);

    this.state = {
        volumes: [{local: 'test', remote: 'test2'}],
    };
  };

  _handleLocalPathData(event, index) {
    const path = event.target.value;
    const data = this.state.volumes[index];
    data.local = path;

    const tmpData = update(this.state.volumes[index], {$set: [data]});

    this.setState({
        volumes: tmpData
    });
 };
}

but volumes aren't the updated one. Where is my mistake?

但是卷不是更新的卷。我的错误在哪里?

2 个解决方案

#1


2  

You want to set local property of object in array at index position:

您想在索引位置的数组中设置object的local属性:

const newVolumes = update(this.state.volumes, {
  [index]: { local: { $set: path },
};
this.setState({ volumes: newVolumes });

#2


0  

make the _handleLocalPathData return the tmpData and inside the class call the function and use this.setState({volumes: tmpData}). why because of the context of this is not refering to the StorageForm class

使_handleLocalPathData返回tmpData并在类内调用该函数并使用this.setState({volumes:tmpData})。为什么因为这个上下文并没有引用StorageForm类

#1


2  

You want to set local property of object in array at index position:

您想在索引位置的数组中设置object的local属性:

const newVolumes = update(this.state.volumes, {
  [index]: { local: { $set: path },
};
this.setState({ volumes: newVolumes });

#2


0  

make the _handleLocalPathData return the tmpData and inside the class call the function and use this.setState({volumes: tmpData}). why because of the context of this is not refering to the StorageForm class

使_handleLocalPathData返回tmpData并在类内调用该函数并使用this.setState({volumes:tmpData})。为什么因为这个上下文并没有引用StorageForm类