>我在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>
);
}
}
我收到错误。
你应该编写代码:
let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })
使用点运算符我们可以实现这一点。
let persons = [...this.state.persons]
persons[0].name= "updated name"
this.setState({ persons })
随着你改变组件状态,下面是不可变更改的示例,我建议您阅读有关如何更改反应状态的文章。或者你可以尝试使用 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')
this.setState(state => (state.persons[0].name = "updated name", state))
假设一些条件检查以找到所需的人员。
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 ]}});
我认为最好的方法是先在临时变量中复制状态,然后在更新该变量后,您可以使用setState
let personsCopy = this.state.persons
personsCopy [0].name= "new name"
this.setState({ persons: personsCopy })
这是我的做法。
看看这是否适合您。
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>