gpt4 book ai didi

javascript - 将元素插入对象

转载 作者:行者123 更新时间:2023-11-30 09:31:03 25 4
gpt4 key购买 nike

我是 React 的新手,但我很确定这个问题与 Javascript 的关系比与 React 的关系更大。我想将自定义元素推送到已在 React 中创建的对象中,而不触发 forceUpdate()

我想将 fullName 推送到 person 对象。所以我可以像这样在 React 中访问它,this.state.person.fullName 而不是 this.state.fullName

现在我知道我可以这样做:this.state.person.fullName = this.formatName(person.name)

但这需要 forceUpdate() 触发重新渲染。我认为这不是推荐的方式。

class Person extends React.Component {
constructor(props) {
super(props);
this.url = "https://randomuser.me/api";
this.state = {
person: {
fullName: '',
},

};

this.generate = this.generate.bind(this);
}

formatName(name) {
// Mr.Jon Snow
return `${name.title}.${name.first} ${name.last}`;
}
generate() {
axios.get(this.url).then(response => {
var person = response.data.results[0];
this.setState({
person: person,
fullName: this.formatName(person.name)
});
});
}
render() {
return (
<div>
<button onClick={this.generate}>Generate</button>
<div className="card">
<h3>The person's information</h3>
<div className="person-name">Name: {this.state.fullName}</div>
<div className="person-dob">Date of Birth: {this.state.person.dob}</div>
<div className="person-email">Email: {this.state.person.email}</div>
<div className="person-phone">Phone Number: {this.state.person.phone}</div>
</div>
</div>
)
}
}

ReactDOM.render(<Person />, document.getElementById('app'));

最佳答案

var person = response.data.results[0];
person.fullName = this.formatName(person.name);
this.setState({
person: person,
});

关于javascript - 将元素插入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46262726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com