简体   繁体   English

在数组状态下更新属性对象reactJS

[英]Update property object in array state reactJS

I have an array Object in my state named object so I have, in my state object in parent component something like: 我有我的状态数组对象命名的对象 ,所以我有,在父组件像我的状态对象:

object:[{id:1, name:"name"},{id:2, name:"name2"}];

And I have a select box in child component for every object in array and select is printed with this.props.object.map passed by props like: 我在子组件中为数组中的每个对象都有一个选择框,并且选择是通过props传递的this.props.object.map打印的:

var elements = this.state.object.map(function(element, k){
        return (

        <Components object={this.state.object} element={element} setPropertyElement={this.setPropertyElement} />         

        )
      }, this);

In child component I have select with change function like: 在子组件中,我具有带有更改功能的选择,例如:

<select className="form-control" ref="name" defaultValue="j" onChange={this.change}>
   <option value="j">j</option>
   <option value="x">x</option>
</select>

So in this case I see in my page 2 elements with related select for change name. 因此,在这种情况下,我在第2页中看到了具有与更改名称相关的选择的元素。 I have my function change . 我有功能变更

change(event){
   this.props.setPropertyElement(this.props.element, event.target.value);
}

In my parent element so I have a function setPropertyElement : 在我的父元素中,所以我有一个函数setPropertyElement

setPropertyElement(element, value){

      element.name = value;
  }

My question is: My operations are correct or I'm modifing in wrong way state object? 我的问题是:我的操作是正确的还是我以错误的方式修改了状态对象? In this case How Can I change correctly value of property object in array? 在这种情况下,如何正确更改数组中属性对象的值?

You are in the right direction. 您的方向正确。 As you already said, to change the state, call the setState({}), where you have to give in which element are you updating. 正如您已经说过的,要更改状态,请调用setState({}),您必须在其中输入要更新的元素。 In this case, if you use the spread operator it should be similar to this: 在这种情况下,如果使用散布运算符 ,则应类似于以下内容:

this.setState({object: [
     ...this.state.object.filter(x => element.ID !== x.ID),
     { id: element.id, name: element.name }
]})

Try this: 尝试这个:

let editableComparatorIndexes = [...this.state.ids];
   editableComparatorIndexes[i] = 1;
   this.setState({editableComparatorIndexes});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM