使用react登录成功后重定向

问题描述 投票:0回答:3

当用户使用电子邮件/密码成功验证时,我需要重定向到另一个页面(组件),否则,在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>

我需要验证角色是否==“ 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": "[email protected]",
            "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": "[email protected]",
            "password": "$2b$10$Bg4nOrNMzc.b/JBNKNiRP.BiMd/.h4CHKiy0nvV/uim0d3VwHl9iq",
            "tickets": [],
            "gains": [],
            "__v": 0
        },
    ........
javascript node.js regex reactjs fetch-api
3个回答
4
投票

对于重定向页面,您可以编写代码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);
    });
 }

1
投票

您将不得不使用一个库来满足您的路由需求。一些流行的是反应路由器,到达路由器etc。从哲学上进行反应,既没有考虑使用哪个路由器,也没有附带它。

假设:您正在使用react-router

然后。

.then(data => {
    this.setState({ items: data.result });
    this.props.history.push('/nextpage');        
})

0
投票

尝试使用history.push

像这样:this.props.history.push('/ RedirectTargetComponent');

© www.soinside.com 2019 - 2024. All rights reserved.