如何使用setState(带有类组件)从对象数组更新单个属性?

时间:2019-06-14 06:19:15

标签: reactjs react-native redux react-redux react-hooks

在this.state中有一个对象数组,我正在尝试从对象数组更新单个属性。

这是我的对象

 this.state = {
  persons: [
    { name: "name1", age: 1 },
    { name: "name2", age: 2 },
    { name: "name3", age: 3 }
  ],
  status: "Online"
};

,我尝试更新人员[0] .name

import React, { Component } from "react";     
class App extends Component {
      constructor() {
        super();
        this.state = {
          persons: [
            { name: "John", age: 24 },
            { name: "Ram", age: 44 },
            { name: "Keerthi", age: 23 }
          ],
          status: "Online"
        };
      }
      changeName() {
        console.log(this);
        this.setState({
         persons[0].name: "sdfsd"
        });
      }

      render() {
        return (
        <button onClick={this.changeName.bind(this)}>change name</button>
        );
      }
    }

出现错误。

7 个答案:

答案 0 :(得分:3)

您应该输入代码:

let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })

答案 1 :(得分:0)

在改变组件状态方面存在问题,下面是不可变更改的示例,建议您阅读有关如何更改反应状态的文章。或者您可以尝试使用Mobx,因为它支持可变性

changePerson(index, field, value) {
  const { persons } = this.state;

  this.setState({
    persons: persons.map((person, i) => index === i ? person[field] = value : person)
  })
}

// and you can use this method 
this.changePerson(0, 'name', 'newName')

答案 2 :(得分:0)

this.setState(state => (state.persons[0].name = "updated name", state))

答案 3 :(得分:0)

假设有条件检查以找到所需的人。

const newPersonsData = this.state.persons.map((person)=>{
    return person.name=="name1" ? person.name="new_name" : person);
                      //^^^^^^^ can be some condition
});

this.setState({...this.state,{person:[...newPersonsData ]}});

答案 4 :(得分:0)

我认为最好的方法是先将状态复制到临时变量中,然后在更新该变量后可以使用setState

let personsCopy = this.state.persons
personsCopy [0].name= "new name"
this.setState({ persons: personsCopy  })

答案 5 :(得分:0)

这就是我要怎么做。

看看是否适合您。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      persons: [
        { name: "John", age: 24 },
        { name: "Ram", age: 44 },
        { name: "Keerthi", age: 23 }
      ],
      status: "Online"
    };
    this.changeName = this.changeName.bind(this);
    this.changeAge = this.changeAge.bind(this);
  }
  
  changeName(value,index) {
    this.setState((prevState)=>{
      const aux = prevState.persons;
      aux[index].name = value;
      return aux;
    });
  }
  
  changeAge(value,index) {
    this.setState((prevState)=>{
      const aux = prevState.persons;
      aux[index].age = value;
      return aux;
    });
  }
    
    render() {
      const personItems = this.state.persons.map((item,index)=>
        <React.Fragment>
          <input value={item.name} onChange={(e)=>this.changeName(e.target.value,index)}/>
          <input value={item.age} onChange={(e)=>this.changeAge(e.target.value,index)}/>
          <br/>
        </React.Fragment>
      );
      
      return(
        <React.Fragment>
          {personItems}
          <div>{JSON.stringify(this.state.persons)}</div>
        </React.Fragment>
      );
      
    }
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

答案 6 :(得分:0)

使用点运算符可以实现这一点。

    let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })