我只想在我从 reducer 更新收到的 props 后在我的表单上运行 onSubmit。
const mapStateToProps = state => {
return {
authError: state.auth.authError // I want this to update before the action.
};
};
如果我在 onSutmit 处理程序中使用 console.log authError,我会收到旧的 authError。第二次运行它时,我收到更新的 authError。
handleSubmit = e => {
e.preventDefault();
console.log("error exists?", this.props.authError);
this.props.signIn(this.state); //dispatches a login action
this.handleHideLogin(); // hides the form after action is dispatched
};
我想仅在分派(dispatch)操作且错误为 null 后隐藏表单。 (认证成功自动返回null)
我尝试使用 setTimeout() 并且它在技术上是可行的,但我想知道是否有更“正确”的方法来做到这一点。
handleSubmit = e => {
e.preventDefault();
this.props.signIn(this.state);
setTimeout(() => {
if (this.props.authError) {
console.log("returns error =>", this.props.authError);
} else {
console.log("no error =>", this.props.authError);
this.handleHideLogin();
}
}, 500);
};
我的部分组件供引用
<form onSubmit={!this.props.authError ? this.handleSubmit : null}>
//the above onSubmit is different if I use the setTimeout method.
<div className="modal-login-body">
<div className="modal-login-input">
<input
type="email/text"
name="email"
autoComplete="off"
onChange={this.handleChange}
required
/>
<label htmlFor="email" className="label-name">
<span className="content-name">EMAIL</span>
</label>
</div>
<div className="modal-login-input">
<input
type="password"
name="password"
autoComplete="off"
onChange={this.handleChange}
required
/>
<label htmlFor="password" className="label-name">
<span className="content-name">PASSWORD</span>
</label>
</div>
</div>
<div className="my-modal-footer">
<p className="login-failed-msg">
{this.props.authError ? this.props.authError : null}
</p>
<button type="submit" className="complete-login-button">
LOGIN
</button>
<a href="CHANGE" className="forgot-password">
<u>Forgot your password?</u>
</a>
</div>
</form>
最佳答案
我假设 this.props.signIn
是一个异步函数。
因此 this.props.authError
是异步更新的,这就是为什么如果您设置超时它在某些情况下会起作用(当您收到短于 5 秒的响应时)。
解决它的一种方法是使用 then
和 catch
而不更新表单的状态
handleSubmit = e => {
e.preventDefault();
this.props.signIn(this.state).then(resp => {
this.setState({userIsValid: true, failure: null})
this.onUpdate(userIsValid);
})
.catch(err => {
this.setState({userIsValid: false, failure: "Failed to login"})
});
}
并使用if-else
来确定是显示表单还是显示您的网站
class App extends React.Component {
render() {
if (this.state.isValidUser) {
return <Main />
} else {
return <LoginForm onUpdate={(isValid) => {this.setState({isValidUser: isValid})} />
}
}
}
换句话说,LoginForm组件存储了用户名、密码、failure(登录失败的错误信息)和isValidUser(判断登录是否成功)。
该应用程序有一个状态来确定要显示的内容、网站或登录组件。使用作为 props 传递给登录组件的 onUpdate
,我们可以更新 App 的状态,并在登录成功时显示网站。
希望对你有帮助。
关于javascript - 如何仅在 props 更新后运行 onSubmit={}?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55793913/