从事件处理函数中测量状态更新

时间:2018-08-03 19:27:53

标签: reactjs

反应小提琴:https://jsfiddle.net/69z2wepo/254140/

我下面有这段代码,用于验证2个电子邮件地址是否匹配。

我发现在select i.xdate, i.xtime, ifnull(o.xtime, 'missing') from (select date(date_time) xdate, time(date_time) xtime from gate_times where gate_op = 'check-in') i left join (select date(date_time) xdate, time(date_time) xtime from gate_times where gate_op = 'check-out') o on i.xdate = o.xdate union all select o.xdate, ifnull(i.xtime, 'missing'), o.xtime from (select date(date_time) xdate, time(date_time) xtime from gate_times where gate_op = 'check-in') i right join (select date(date_time) xdate, time(date_time) xtime from gate_times where gate_op = 'check-out') o on i.xdate = o.xdate where i.xdate is null order by 1, 2, 3 内部没有立即识别出状态更新。也就是说,代码段handleChange需要再次调用handleChange才能捕获状态更新。

(我能够使用另一种技术解决我原来的问题。我将代码段this.state.email === this.state.email2...的版本直接放在this.state.email === this.state.email2...内)。

我的问题:您将如何修改代码,以便代码段<span>立即识别出状态已更新?似乎这需要回调函数或方法链接。 (我鼓励更多有经验的开发人员为清楚起见,请编辑我的问题。)

this.state.email === this.state.email2...

自我解答后的注释,以供将来参考:setState是异步的,因此发生了此问题。通过将代码段包装在class Signup extends React.Component{ constructor(props) { super(props); this.state = { email: "", email2: "", email_match_message: "" }; } render() { return( <div> <div> email: <input type="email" name="email" value={ this.state.email } onChange={ this.handleChange } /><br /> email2: <input type="email" name="email2" value={ this.state.email2 } onChange={ this.handleChange } /><span>{ this.state.email_match_message }</span><br /> </div> </div> ) } handleChange = ({ target }) => { this.setState({ [target.name]: target.value }); this.state.email === this.state.email2 ? this.setState({email_match_message: "emails match"}): this.setState({email_match_message: "emails don't match"}); } } 中以延迟其执行,我也能够解决此问题(小提琴:https://jsfiddle.net/69z2wepo/254200/

1 个答案:

答案 0 :(得分:1)

handleChange = ({ target }) => {
    this.setState({
        [target.name]: target.value
    }, () => {
        const { email, email2 } = this.state;
        email === email2 ? this.setState({email_match_message:"emails match"}) : this.setState({email_match_message: "emails don't match"});
    });
}

此代码将解决您的问题,因为它会等到setState完成。但是,在最佳情况下,您不会在一个函数中设置两次setState。可能是这样的:

handleChange = ({ target }) => {
    const oppositeEmail = target.name === "email" ? "email2" : "email";
    const changedEmail = target.value;

    const emailMatchMessage = changedEmail === this.state[oppositeEmail] ? "emails match" : "emails dont match";

    this.setState({
        [target.name]: target.value,
        email_match_message: emailMatchMessage
    });    //added a closing paren
}