如何为 {items.name} 一个位于构造函数 -> this.state -> 项中的对象执行 setState: { name: '', age:'' }
在构造函数中,您可以在执行setState
时将值分配给this.state
this.state = {
name: "",
age: ""
}
但是很少有用例需要以这种方式执行此操作。
如果需要设置 bugDetail 的状态,
在构造函数中,您可以执行以下操作:
constructor(props) {
super(props);
this.state = { bugTitle : '',
bugDescription : '',
bugType : '',
bugDetail : { title : '', description : '', type: '' },
bugDetailArray : [] } }
稍后执行以下操作:->
this.setState({bugDetail:{title:"updated",description : 'olderdesc', type:"older"}})
也可以做:->
updateTitle(updatedTitle){
let newBugdetail = this.state.bugDetail;
newBugdetail.title = updatedTitle;
this.setState({bugDetail:newBugdetail })
}
否则,您需要将标题保留为状态中的外部键
我相信你的构造函数看起来像这样
constructor(props) {
super(props);
this.state = {
bugTitle : '',
bugDescription : '',
bugType : '',
bugDetail : {
title : '',
description : '',
type: ''
},
bugDetailArray : []
}
}
所以为了在函数中使用setState
更改状态
someFunction = (e) => {
let inputName = e.target.name;
let inputValue = e.target.value;
let updatedFormState = Object.assign({}, this.state);
updatedFormState.bugDetail["title"] = inputValue;
this.setState(updatedFormState);
}