【问题标题】:State Change Isn't Saving in React and Mongoose?状态更改不是在 React 和 Mongoose 中保存吗?
【发布时间】: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


    【解决方案1】:

    您的代码完全正确,console.log 正在打印正确的内容。您正在 onCheck 方法中执行 console.log ——它正在打印当前值。

    发生的情况是,当您执行set state 时,会异步调用生命周期方法来更新组件并设置状态。因此,如果您在设置状态(同步)之后立即执行状态的console.log,它将打印先前的状态,因为它尚未更新。

    以下是被调用的生命周期方法:

    1. shouldComponentUpdate
    2. componentWillUpdate
    3. componentDidUpdate

    因此,如果您想检查值是否已更新,您应该在componentDidUpdate 中执行console.log。它会告诉您更新后的状态。

    为了解释工作原理,我在code sandbox 上为您创建了一个简短的演示,其中包含您的代码示例。这解释了工作并表明您的代码是正确的。

    现在,就 Mongoose 没有更新值而言,如果不查看您的代码,我无话可说。您在更新值的代码中一定有一些错误。我不确定,但请交叉检查您是否使用与submit 相同的页面进行更新,确保将请求从post 更改为put,并检查如何使用Mongoose 更新值。

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多