在axios成功登录后重定向页面 - reactJS

时间:2017-09-06 17:58:46

标签: php reactjs symfony

我正在尝试使用react创建一个登录页面。我提交表单并将数据发送到服务器(PHP / Symfony),在那里我运行登录逻辑并返回带有成功或错误数据的JSON对象。 然后,如果用户数据正确并且登录正常,我需要将他重定向到另一个页面。我正在使用反应state.

LoginComponent.js

import React, { Component } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import {Link} from 'react-router-dom';
const browserHistory = createBrowserHistory();

class LoginComponent extends Component {

  constructor(props) {
    super(props);

    this.state = {
      errors: {},
      login:'',
      password:'',
      fireRedirect: false
    };

    this.processForm = this.processForm.bind(this);
  }

  processForm(event) {
    event.preventDefault();

    const login = this.state.login;
    const password = this.state.password;
    //TODO validation

    const formData = { login:login, password:password };

    axios.post('http://myweburl.org/app/web/login', formData, { headers: {'Accept': 'application/json'} })
      .then((response) => {

        if(response.data.success) {
          this.setState({ fireRedirect: true })
        }else if(response.data.error){
            this.setState({
            errors:response.data.error
          });
        }
      });
  }

  handleLoginChange(e) {
    this.setState({login: e.target.value});
  }

  handlePasswordChange(e) {
    this.setState({password: e.target.value});
  }

  render() {
    //const { fireRedirect } = this.state;
    if(this.state.fireRedirect) {
        return <Redirect to={'/obligation'}/>
    }

    return (
      <div className="wrapper">
        <div className="full-content">
            <div className="login-page">
              <div className="egz-logo"><img src={`/img/logo.png`} alt="MyEGZ" title="MyEGZ"/></div>
              <form autoComplete="off" onSubmit={this.processForm}>
                <div className="login-block">
                  <input type="text" name="login" value={this.state.login} onChange={this.handleLoginChange.bind(this)} placeholder="login" id="client-login"/>
                </div>
                <div className="login-block">
                  <input type="password" autoComplete="off" name="password" value={this.state.password} onChange={this.handlePasswordChange.bind(this)} placeholder="mot de passe" id="client-pwd"/>
                </div>
                <div className="login-block">
                  <input type="checkbox" name="remember-me" id="client-remember-me"/>
                  <label>Se souvenire de moi</label>
                </div>
                <div className="login-button-block">
                  <input type="submit" name="login-submit" id="login-submit" value="Connexion"/>
                  <div >
                    <Link key="forgot-pwd" to={`/login/forgetpassword`}>
                      mot de passe oubile
                    </Link>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    );
  }
}

export default LoginComponent;

App.js

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import './index.css';
import { Router,Route } from 'react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import Obligation from './components/obligation/ObligationComponent';
import Contacts from './components/contacts/ContactComponent';
import ContactPage from './components/contacts/ContactPage';
import LoginPage from './components/LoginComponent';
const browserHistory = createBrowserHistory();

function auth() {

  axios.post('http://myweburl.org/app/web/checkLogin', { headers: {'Accept': 'application/json'} })
    .then((response) => {
      console.log(response);
      if(response.data.success){
        return true;
      }else if(response.data.error){
        return false;
      }
    });

};

const isAuthorized = auth();

ReactDOM.render(
    <Router history={browserHistory}>
      <div>
        <Route exact path="/" component={() => <LoginPage isAuthorized={isAuthorized} />} />
        <Route path="/obligation" component={() => <Obligation title="Obligations légales" isAuthorized={isAuthorized} style="home-header"/> }/>
        <Route path='/contacts' component={() => <Contacts title="Contacts" isAuthorized={isAuthorized} style="contact-header" />} />
        <Route path="/contact/:id" component={() => <ContactPage isAuthorized={isAuthorized} />}/>
      </div>
    </Router>,
  document.getElementById("root")
);

当我使用正确的数据提交表单时,它会返回正确数据的成功 { “成功”:1, “数据”:{ “clients_id”: “2”}} 和loginComponent ajax中的打印响应数据成功它也会返回我 -

  

的console.log(response.data.success,this.state.fireRedirect);

     

1 true

但重定向不起作用。我做错了什么?

3 个答案:

答案 0 :(得分:1)

这是我通常进行api调用的方式。

axios
                .post("/yourApiEnd", {
                    accounts: this.accounts
                })
                .then(function(response) {
                    const status = response.status;
                    //redirect logic
                    if (response.status == 200) {
                            window.location = "/script" 
                    }
                })
                .catch(e => {
    console.error(e);
  });
        }

答案 1 :(得分:0)

<Redirect to='/obligation'/>

<Redirect to={this.props.someVar}/>

<Redirect to={something}/>

但你使用花括号来解析js并在其中提供字符串。

答案 2 :(得分:0)

LoginComponent.js 中,您已经使用状态在成功登录时触发。 现在您需要在代码处触发它。 您可以在渲染器上添加一条语句以触发重定向

...  
return (
      <div className="wrapper">
{this.state.fireRedirect && <Redirect to="location" />}
相关问题