【发布时间】:2019-06-14 06:19:15
【问题描述】:
我在 this.state 中有一个对象数组,我正在尝试更新对象数组中的单个属性。
这是我的对象
this.state = {
persons: [
{ name: "name1", age: 1 },
{ name: "name2", age: 2 },
{ name: "name3", age: 3 }
],
status: "Online"
};
我尝试更新 people[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>
);
}
}
我遇到了一个错误。
【问题讨论】:
-
如果您可以展示更多代码或示例,那将是理想的,因为使用这个 sn-p 代码,我们没有太多信息......
-
@john_ny 你为什么选择这个答案?
标签: reactjs react-native redux react-redux react-hooks