登录后反应重定向 [英] React redirect after login

查看:69
本文介绍了登录后反应重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 应用中有一个 ajax 登录.它处理 LoginForm 组件.应用程序还使用 React 路由器ajax 登录后,我想做一些类似重定向到另一个 React 页面的事情.我不知道如何在成功登录后正确地从登录页面重定向到主页.有人可以帮我吗?我正在使用类样式来制作组件.

这是来自 LoginForm 组件的代码:

 sendData(e){e.preventDefault();this.setState({'errors': [], 'success': []});让 formData = new FormData();formData.set('name', this.state.name);formData.set('password', this.state.password);轴({方法:'POST',//url: 'http://localhost:8000/login'数据:表单数据,标题:{'内容类型':'文本/html','X-Requested-With': 'XMLHttpRequest',}}).then(响应 => {//这里应该是重定向到另一个 React 页面}).catch(响应 => {this.setState({errors: ['登录失败.请稍后再试.']})});}

React 路由器看起来像

<ul className="navbar-nav mr-auto"><li className="nav-item"><NavLink to="/";className=nav-link">主页<li className="nav-item"><NavLink to="/login";className=nav-link">登录<li className="nav-item">关于

<div className="container-fluid"><div><开关><路由路径="/";精确><首页/></路线><路由路径=/登录"><登录/></路线><路线路径=/about";组件={关于}/></开关>

解决方案

如果你正在使用功能组件,你可以使用 react-router-domuseHistory 钩子>.

成功登录后,重定向到主页,如下所示:

import { useHistory } from 'react-router-dom';const 登录 = () =>{const routerHistory = useHistory();...const sendData = (e) =>{....then(响应 => {//这里应该是重定向到另一个 React 页面routerHistory.push('/');})...}...}

您还可以使用 history 道具,它是从 React Router 传递的道具之一.这也适用于基于类的组件.

类登录{...发送数据(e){....then(响应 => {//这里应该是重定向到另一个 React 页面this.props.history.push('/');})...}...}

如果 Login 组件由于应用程序中组件的层次结构而没有传递路由道具,那么您可以使用 withRouter 高阶组件来访问 history 对象.

import { withRouter } from react-router";类登录{...}导出默认 withRouter(Login);

详情见:

I have a ajax login in React app. It handles LoginForm component. Aplication also uses React router After ajax login I would like to make something like redirect to another React page. I dont know how to properly redirect from login page to homepage after successful login. Can somebody help me please? I am using class style to making components.

This is the code from LoginForm component:

    sendData(e)
    {
        e.preventDefault();
        this.setState({'errors': [], 'success': []});

        let formData = new FormData();
        formData.set('name', this.state.name);
        formData.set('password', this.state.password);

        axios({
            method: 'POST',
            //url: 'http://localhost:8000/login'
            data: formData,
            headers: {
                'Content-Type': 'text/html',
                'X-Requested-With': 'XMLHttpRequest',
            }
        })
            .then(response => {
               // Here should be the redirect to another React page
            })
            .catch(response => {
                this.setState({errors: ['Login fails. Try it again later please.']})
            });
    }

React Router looks like

<div className="collapse navbar-collapse" id="navbarSupportedContent">
    <ul className="navbar-nav mr-auto">
        <li className="nav-item">
            <NavLink to="/" className="nav-link">Home</NavLink>
        </li>
        <li className="nav-item">
            <NavLink to="/login" className="nav-link">Login</NavLink>
        </li>
        <li className="nav-item">
            <NavLink to="/about" className="nav-link">About</NavLink>
        </li>
    </ul>
</div>
<div className="container-fluid">
    <div>
        <Switch>
            <Route path="/" exact>
                <Home />
            </Route>
            <Route path="/login">
                <Login />
            </Route>
            <Route path="/about" component={About}/>
        </Switch>
    </div>
</div>

解决方案

If you are using functional components, you can use use useHistory hook provided by react-router-dom.

On a successful login, redirect to home page as shown below:

import { useHistory } from 'react-router-dom';

const Login = () => {
   const routerHistory = useHistory();
   ...

   const sendData = (e) => {
      ...
      .then(response => {
         // Here should be the redirect to another React page
         routerHistory.push('/');
      }) 
      ...
   }
   
   ...
}

You could also use history prop which is one of the prop passed from React Router. This will work in class based components too.

class Login {
     ...

     sendData(e) {
        ...
        .then(response => {
           // Here should be the redirect to another React page
           this.props.history.push('/');
        })
        ...
     } 

    ...
}

If Login component is not passed router props because of the hierarchy of the components in your app, then you can use withRouter higher order component to get access to history object.

import { withRouter } from "react-router";

class Login {
   ...
}

export default withRouter(Login);

For details see:

这篇关于登录后反应重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆