如果我单击按钮以更新名称,那么它不会使用setState更改,我想更新person变量,并且也应该在DOM中更新。
请向我建议如何更新状态
App.js
import React, { Component } from "react";
import Person from "./component/Person";
import "./App.css";
class App extends Component {
constructor() {
super();
this.state = {
persons: [
{ name: "max", age: 28 },
{ name: "manu", age: 29 },
{ name: "step", age: 26 }
]
};
}
chnagenames = () => {
console.log("clicked me ");
this.setState = {
persons: [
{ name: "maxi", age: 28 },
{ name: "manr", age: 29 },
{ name: "step", age: 27 }
]
};
console.log(this.state.persons);
};
render() {
return <> {/* ... */} </>;
}
}
export default App;
Person.js
import React from "react";
const Person = props => {
return (
<>
person age is {props.ages} and name is {props.attrib}{" "}
</>
);
};
export default Person;
答案 0 :(得分:1)
您应该调用this.setState
,因为它是一个函数,而不是为其分配新值。
您在chnagenames
方法上也有错字,并且setState
也是异步的,因此如果直接在setState
之后记录更改,您将看不到更改。
changenames = () => {
console.log("clicked me ");
this.setState(
{
persons: [
{ name: "maxi", age: 28 },
{ name: "manr", age: 29 },
{ name: "step", age: 27 }
]
},
() => console.log(this.state.persons)
);
};
答案 1 :(得分:0)
请尝试以下操作:
chnagenames = () => {
console.log("clicked me ");
var changedArray = [
{ name: "maxi", age: 28 },
{ name: "manr", age: 29 },
{ name: "step", age: 27 }
];
this.setState({
persons: changedArray
}, function {
console.log(this.state.persons);});
};