【发布时间】:2019-08-11 03:06:12
【问题描述】:
我无法更改复选框状态。我的 Mongoose 模型中的默认选项是 false。当他们检查并仅在第一次提交时,我可以成功地更新用户的个人资料(它将更改为 true),但是当他们返回编辑个人资料(相同的路线)并 $set 个人资料字段时,它不会将“displayEmailOnProfile”的布尔值更改为 false。它只是保持检查状态。 console.logs() 也有点奇怪。选中该框时,它会打印出 true,然后 displayEmailOnProfile 的状态为 false。取消选中时,displayEmailOnProfile 的状态为真?
然后当我点击提交时,它没有更新猫鼬模型上的任何内容?
constructor (props) {
super(props);
this.state = {
displayEmailOnProfile: false,
errors: {}
}
this.onSubmit = this.onSubmit.bind(this);
this.onCheck = this.onCheck.bind(this);
}
componentWillReceiveProps(nextProps) {
// Set component fields state
this.setState({
displayEmailOnProfile: profile.displayEmailOnProfile,
});
}
}
onChange = (e) => {
this.setState({[e.target.name]: e.target.value});
}
onSubmit = (e) => {
e.preventDefault();
const profileData = {
displayEmailOnProfile: this.state.displayEmailOnProfile
}
this.props.createProfile(profileData, this.props.history);
}
onCheck = (e) => {
console.log(this.state);
console.log(e.currentTarget.checked);
this.setState({
displayEmailOnProfile: e.currentTarget.checked
});
}
这里是 HTML / React 标记
<div className="form-check mb-4">
<input className="form-check-input" type="checkbox" id="defaultCheck1" name="displayEmailOnProfile" checked={this.state.displayEmailOnProfile} onChange={this.onCheck}></input>
<label class="form-check-label" for="customCheck1">Display Email On Profile</label>
</div>
【问题讨论】:
标签: javascript reactjs mongoose