【发布时间】:2019-03-24 17:02:18
【问题描述】:
我在设置状态下的对象键时遇到问题。所以下面的代码是一个带有标题、正文、城市和国家的表格。使用用户给出的值,我将它们设置为状态。但是由于国家和城市应该在“地址”对象中分配,我创建了一个处理程序来检查值是否是国家/城市。
但是结果即使不满足条件,ELSE在运行,它仍然使用if条件中的对象assign。
所以无论是标题还是城市,状态都是在地址对象中设置的
你会检查我哪里做错了吗?
下面是我的表单和处理程序
class Postit extends Component {
state = {
title: "",
body: "",
address: {
country: "",
city: ""
}
};
handleChange = e => {
if (e.target.id === "country" || "city") {
let address = Object.assign({}, this.state.address);
address[e.target.id] = e.target.value;
this.setState({ address });
console.log("NewState", this.state);
} else {
console.log("Target is not city or country");
this.setState({
[e.target.id]: e.target.value
});
}
};
handleSubmit = e => {
e.preventDefault();
console.log(this.state);
};
render() {
return (
<div className="container">
<form className="white" onSubmit={this.handleSubmit}>
<h5 className="grey-text text-darken-3">Send your post</h5>
{/* Title */}
<div className="input-field">
<input type="text" id="title" onChange={this.handleChange} />
<label htmlFor="title"> Title</label>
</div>
{/* Body */}
<div className="input-field">
<textarea
id="body"
className="materialize-textarea"
onChange={this.handleChange}
/>
<label htmlFor="body"> Content</label>
</div>
{/* City / Country Select */}
<div className="input-field">
<input type="text" id="country" onChange={this.handleChange} />
<label htmlFor="country"> Write your Country</label>
</div>
<div className="input-field">
<input type="text" id="city" onChange={this.handleChange} />
<label htmlFor="city"> Write your City</label>
</div>
<div className="input-field">
<button
className="btn pink lighten-1 center-align"
style={{ marginTop: "10px", borderRadius: "6px", width: "100%" }}
>
Post it
</button>
</div>
</form>
</div>
);
}
}
例如,当我填写标题时,newState 是这样的:
{title: "", body: "", address: {country:"", city:"", title:"test"}}
谢谢!
【问题讨论】:
标签: reactjs object event-handling setstate