gpt4 book ai didi

javascript - 使用react登录成功时重定向

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:24 27 4
gpt4 key购买 nike

当用户使用电子邮件/密码成功验证时,我需要重定向到另一个页面(组件),否则,在 div 上显示一条警告消息,提示电子邮件或密码不正确。

这是我的代码:

 constructor (props) {
super(props);
this.state = {
// name: "",
cnx_mail: '',
cnx_pwd: '',
joinByEmail: '',
items: [],
token : '',
redirectToReferrer:false,
errors: {},

formErrors: {cnx_mail: '', cnx_pwd: ''},
emailValid: false,
passwordValid: false,
formValid: false
}
this.handleUserInput = this.handleUserInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit = (event) => {
event.preventDefault();
fetch(`${API}/api/connexion`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify ({
email: this.state.cnx_mail,
password: this.state.cnx_pwd,
})
})
.then(res => res.json())
.then(json => {
console.log(json);
localStorage.setItem('toktok', json.result);
console.log(json[0].role);
//i have to verify email/password bedore redirection
window.location.href="/accounts";
});
}

这是我在 render() 中的形式:

<form className="demoForm" onSubmit={this.handleSubmit} noValidate  encType="application/x-www-form-urlencoded">
<div className="alreadysubscribed-input">
<div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_mail)}`}>
<input type="email" required className="form-control fatb-input input-form" name="cnx_mail"
value={this.state.cnx_mail}
id="cnx_mail"
onChange={this.handleUserInput} error={errors.cnx_mail} />
<label className="fatb-label" htmlFor="cnx_mail">Email</label>
<div className="fatb-bar"></div>
</div>

<div className={`alreadysubscribed-field group-input ${this.errorClass(this.state.formErrors.cnx_pwd)}`}>
<input type="password" required className="form-control fatb-input input-form" name="cnx_pwd"
value={this.state.cnx_pwd}
id="cnx_pwd"
onChange={this.handleUserInput} error={errors.cnx_pwd} />
<label className="fatb-label" htmlFor="cnx_pwd">Mot de passe</label>
<div className="fatb-bar"></div>
</div>
</div>
<FormErrors formErrors={this.state.formErrors} />

<div className="btn-cnx">
{/* <span className="mas">Se connecter</span> */}
<button className="fatb-btn bubbly-button btn-anim3 w100p" type="submit" name="cnx_btn" disabled={!this.state.formValid}>se connecter</button>
</div>
</form>

我需要验证 Angular 色是否==“admin”,然后重定向到/accounts,否则在 div 中显示警告消息。

这是我的数据结构:

{
"success": true,
"message": "SUCCESS",
"result": [
{
"dateCreation": "2019-10-09T21:54:18.491Z",
"resetpasswordtoken": null,
"resetpasswordexpires": null,
"role": "admin",
"enable": true,
"_id": "5d9e67772682971c1fc3711c",
"email": "meachemlal@gmail.com",
"password": "$2b$10$HqEMSkaWBZ..BFvSpxliUu/02vWodvxYoFZMaYUU5ZsBeqeZB4jLu",
"tickets": [],
"gains": [],
"__v": 0,
"nom": "ACHEMLAL",
"prenom": "MERYEM",
"tel": "+33619562721"
},
{
"dateCreation": "2019-10-09T21:54:18.491Z",
"resetpasswordtoken": null,
"resetpasswordexpires": null,
"role": "admin",
"enable": true,
"_id": "5d9e677e2682971c1fc3711d",
"email": "mika.achemlal@gmail.com",
"password": "$2b$10$Bg4nOrNMzc.b/JBNKNiRP.BiMd/.h4CHKiy0nvV/uim0d3VwHl9iq",
"tickets": [],
"gains": [],
"__v": 0
},
........

最佳答案

对于重定向页面,您可以编写代码window.location.href,如下所述。

componentDidMount() {
const token = localStorage.getItem('toktok');
fetch(`${API}/api/accounts`,{
headers :{
'authorization': `Bearer ${token}`,
}
})
.then(results => {
return results.json();
})
.then(data => {
this.setState({ items: data.result });
window.location.href="/nextpageurl";
})
.catch(err => {
console.log("error : ",err);
});
}

还有重定向页面验证之前:-

  import { AvForm,AvField} from 'availity-reactstrap-validation';
<AvForm onValidSubmit={this.onSubmit} name="login" className="app_start_form">
<div className="form-group">
<span className="icon"><img src={email} alt="" /></span>
<AvField type="text" ng-model="user.Email" name="username" value={this.state.username} onChange={this.onChange} className="form-control" placeholder="Email/Mobile No.*"
validate={{
pattern: { value: /^((([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))|([0-9]{9,}))\w+$/, errorMessage: 'Please enter valid emailid or mobile no' },
required: { value: true, errorMessage: "Email or Mobile No. is required" },
maxLength: { value: isMobile, errorMessage: 'Mobile No. must be maximum '+isMobile+' digits' }
}} />
<AvField type="password" name="password" autoFocus value={this.state.password} onChange={this.onChange} className="form-control" placeholder="Password *"
validate={{
required: { value: true, errorMessage: "Password is required" },
pattern: { value:/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/, errorMessage: 'Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit' },
minLength: { value: 8, errorMessage: 'Password must be at least 8 characters' },
maxLength: { value: 20, errorMessage: 'Password not more then 20 characters' }
}} />
</div>

<div className="sec_btn loginbtn_ind">
<button type="submit" className="btn blue_btn">SIGN IN</button>
</div>
</AvForm>

关于javascript - 使用react登录成功时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58540547/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com