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

Joh*_*_ny 0 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"
};
Run Code Online (Sandbox Code Playgroud)

我尝试更新人 [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>
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)

出现错误。

小智 5

你应该编码:

let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })
Run Code Online (Sandbox Code Playgroud)