简体   繁体   English

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

[英]redirect page after axios success login - reactJS

I am trying to create a login page with react.我正在尝试创建一个带有反应的登录页面。 I submit the form and send data to the server (PHP/Symfony) where I run login logic and return JSON object with success or error data.我提交表单并将数据发送到服务器(PHP/Symfony),在那里我运行登录逻辑并返回带有成功或错误数据的 JSON 对象。 Then if user data is right and login is ok, I need to redirect him to another page.然后如果用户数据正确并且登录没问题,我需要将他重定向到另一个页面。 I am using react state.我正在使用反应state.

LoginComponent.js登录组件.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应用程序.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")
);

When I submit form with right data, it returns success with correct data {"success":1,"data":{"clients_id":"2"}} and the print response data in loginComponent ajax success it also returns me this -当我用正确的数据提交表单时,它返回成功并返回正确的数据 {"success":1,"data":{"clients_id":"2"}} 和 loginComponent ajax success 中的打印响应数据,它也返回给我这个 -

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

1 true 1 真

But redirect is not working.但是重定向不起作用。 What am I doing wrong?我究竟做错了什么?

This is how i usually do my api calls.这就是我通常进行 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);
  });
        }
<Redirect to='/obligation'/>

or或者

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

or或者

<Redirect to={something}/>

but you used curly braces for js resolving and provided string in them.但是您使用花括号进行 js 解析并在其中提供字符串。

in LoginComponent.js you have already used the state to trigger when successful login happens.LoginComponent.js 中,您已经使用了成功登录时触发的状态。 now you need to trigger that at code .现在您需要在 code 处触发它。 You can add a statement at the render to trigger the redirect您可以在渲染中添加语句以触发重定向

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM