[英]How to send a POST request conditionally to login or sign up users
我正在嘗試根據我的 state 中的prop
( isSignUp
) 是true
還是false
,向用戶發送 POST 請求 SIGN UP 或 LOGIN 。
我想要發生的事情:
如果isSignUp
為真,我希望一個 API 端點被命中,如果不是,另一個被命中。
各個端點都可以工作,但是當我將所有東西連接起來時,我只能讓人們登錄,而一旦他們注冊就無法登錄。
State:
state = {
controls: {
email: {
elementType: "input",
elementConfig: {
type: "email",
placeholder: "Email Address"
},
value: "",
validation: {
required: true, // must not be empty
isEmail: true
},
valid: false,
touched: false
},
isSignUp: true
}
};
處理程序:
handleSubmit = event => {
this.props.onAuth(
this.state.controls.email.value,
this.state.controls.password.value,
this.state.controls.isSignUp
);
event.preventDefault();
};
switchAuthModeHandler = () => {
this.setState(prevState => {
console.log(prevState);
return {
isSignUp: !prevState.isSignUp
};
});
};
切換按鈕文本和觸發 authModeHandler 的邏輯
return (
<div className={classes.Auth}>
<form onSubmit={this.handleSubmit}>
{form}
<Button btnType="Success">SUBMIT</Button>
</form>
<Button clicked={this.switchAuthModeHandler} btnType="Danger">
SWITCH TO {this.state.isSignUp ? "SIGN IN" : "SIGN UP"}
{console.log(this.state.isSignUp)}
</Button>
</div>
);
const mapDispatchToProps = dispatch => {
return {
onAuth: (email, password, isSignUp) =>
dispatch(actions.auth(email, password, isSignUp))
};
};
觸發 POST 請求以登錄或注冊用戶的操作
export const auth = (email, password, isSignUp) => {
return dispatch => {
dispatch(authStart());
const authData = {
email: email,
password: password,
returnSecureToken: true
};
{
isSignUp
? axios
.post(
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIzaSyAGT2vM3uzywo3zQUAxNnkpPB6Yr3Ohets",
authData
)
.then(response => {
console.log(response);
dispatch(
authSuccess(response.data.idToken, response.data.userId)
);
})
: axios
.post(
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=AIzaSyAGT2vM3uzywo3zQUAxNnkpPB6Yr3Ohets",
authData
)
.then(response => {
console.log(response);
dispatch(
authSuccess(response.data.idToken, response.data.userId)
);
})
.catch(err => {
console.log(err);
dispatch(authFail(err));
});
}
};
};
在 State 中,您將isSignup
置於不在控制之下,因此您應該通過this.state.isSginUp
訪問它
handleSubmit = event => {
this.props.onAuth(
this.state.controls.email.value,
this.state.controls.password.value,
this.state.isSignUp
);
event.preventDefault();
};
PS 我建議使用 Redux 開發工具。 它可以挽救生命。 快樂編碼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.