![](/img/trans.png)
[英]index.js:1 Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument
[英]setState updates state however callback function as second argument will not execute
我正在更改登录功能的逻辑。 我有一个用于signUp
的按钮和一个用于signIn
的按钮。 signUp
有效,但signIn
无效,我不确定为什么当它们都导致相同的 function 启动 api 请求以登录用户时。
state:
state = {
controls: {
email: {
elementType: "input-email",
elementConfig: {
type: "email",
placeholder: "Email Address"
},
value: localStorage.getItem("email") || "",
validation: {
required: true, // must not be empty
isEmail: true
},
valid: false,
touched: false
},
password: {
elementType: "input",
elementConfig: {
type: "password",
placeholder: "Password"
},
value: "",
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
}
},
isSignUp: true,
rememberMe: false
};
使用两个按钮登录表单代码:
return (
<div className={classes.Auth}>
{isLoggedIn}
{errorMessage}
<p className={classes.signUp}>Sign up to create a burger</p>
<form onSubmit={this.handleSubmit}>
{form}
<Button btnType="Success">SIGN UP </Button>
</form>
<p className={classes.subText}>
Already have an account? Switch to sign in below:
</p>
<Button clicked={this.signInHandler} btnType="Danger">
SIGN IN
</Button>
</div>
);
两个按钮的处理程序:
Signup
处理程序(这有效):
handleSubmit = event => {
this.props.onAuth(
this.state.controls.email.value,
this.state.controls.password.value,
this.state.isSignUp
);
event.preventDefault();
};
然后还调用SignIn
handleSubmit
处理程序:
signInHandler = () => {
this.setState(
{ isSignUp: false }, // should be false to kick off the api for the SignIn
() => { // callback
this.handleSubmit(); // calls the method above which signs user in
}
);
};
我按照这个stackoverflow
线程写了这部分: setState doesn't update the state
这是我单击“登录”按钮时遇到的错误
TypeError: Cannot read property 'preventDefault' of undefined
任何想法为什么?
您缺少事件参数。 这应该有效:
signInHandler = (e) => {
this.setState(
{ isSignUp: false }, // should be false to kick off the API for the SignIn
() => { // callback
this.handleSubmit(e); // calls the method above which signs user in
}
);
};
您正在调用handleSubmit = event =>
,但没有发送事件来处理提交,请将其添加到流程中
<Button clicked={e=>this.signInHandler(e)} ... />
signInHandler = e => {
this.setState(
{ isSignUp: false }, // should be false to kick off the api for the SignIn
() => { // callback
this.handleSubmit(e); // calls the method above which signs user in
}
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.