首页 > 解决方案 > 登录 React.js 后重定向

问题描述

几天以来,我一直在尝试在登录到主页后重定向我的用户,在我的 App.js 中创建一个回调函数,并通过 loginregisterpage 类组件将其作为道具发送到登录类组件,但这不起作用,有人可以吗看看它,告诉我我错过了什么?谢谢我的代码看起来像这样

应用程序.js

import React from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import { HomePage } from './Pages/HomePage/HomePage'
import { LoginRegisterPage } from './Pages/LoginRegisterPage/LoginRegisterPage'
import 'bootstrap/dist/css/bootstrap.min.css'

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      authenticated: false,
    }
    this.handleSuccess = this.handleSuccess.bind(this);

  }
  handleSuccess = (data) => {
    this.props.history.push("/")
  }

  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/">
            <HomePage />
          </Route>
          <Route exact path="/login-register">
            <LoginRegisterPage onLoginSuccess={this.handleSuccess} />
        </Switch>
      </Router>
    )
  }
}

LoginRegisterPage 类组件

class LoginPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            accessToken: '',
            authenticated: ''
        };
        this.handleChangeUsername = this.handleChangeUsername.bind(this);
        this.handleChangePassword = this.handleChangePassword.bind(this);

    }

    handleChangeUsername(event) {
        this.setState({
            username: event.target.value
        })
    }

    handleChangePassword(event) {
        this.setState({
            password: event.target.value
        })
    }

    handleClick(event) {
        var apiBaseUrl = "https://myapi.com/auth/"
        const payload = {
            method: "POST",
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify({
                'username': this.state.username,
                'password': this.state.password
            })
        };
        const { username, password } = this.state;

        if (username && password) {
            fetch(apiBaseUrl + 'login', payload)
                .then((response) => {
                    if (response.status === 200) {
                        alert("Logged In! You'll be redirected on Home")
                        return response.json()
                    } else {
                        return alert("wrong pass")
                    }
                }).then((data) => {
                    this.setState({
                        accessToken: data.accestToken,
                        authenticated: data.authenticated
                    });
                    localStorage.setItem('accessToken', data.accessToken);
                    if (data.authenticated === true) {
                        console.log(this.props)
                        this.props.onLoginSuccess(data)
                    }

                })
                .catch((err) => console.log(err));
        } else {
            alert("Cannot be Empty")
        }
    }

    render() {
        return (
            <div>
                <div className="form">
                    <div>
                        <div className="form-input">
                            <div >
                                <div className="userData">
                                    <span>
                                        <img
                                            src={UserIcon}
                                        />
                                    </span>
                                    <input
                                        autocomplete="off"
                                        type="text"
                                        name="username"
                                        placeholder="Username"
                                        value={this.state.username}
                                        onChange={this.handleChangeUsername}
                                    />
                                </div>
                                <div className="userData">
                                    <span>
                                        <img
                                            src={PasswordIcon}
                                        />
                                    </span>
                                    <input
                                        autocomplete="off"
                                        type="password"
                                        name="password"
                                        placeholder="Password"
                                        value={this.state.password}
                                        onChange={this.handleChangePassword}
                                    />
                                    <p style={(this.state.username && this.state.password) ? { display: 'none' } : { display: 'block' }}> Must fill all the form!</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="form-footer">
                    <img
                        src={Btn}
                        onClick={(event) => this.handleClick(event)}
                    />
                </div>
            </div>
        );
    }
}

LoginPage 类组件

class LoginPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
            accessToken: '',
            authenticated: ''
        };
        this.handleChangeUsername = this.handleChangeUsername.bind(this);
        this.handleChangePassword = this.handleChangePassword.bind(this);

    }

    handleChangeUsername(event) {
        this.setState({
            username: event.target.value
        })
    }

    handleChangePassword(event) {
        this.setState({
            password: event.target.value
        })
    }

    handleClick(event) {
        var apiBaseUrl = "https://movies-app-siit.herokuapp.com/auth/"
        const payload = {
            method: "POST",
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            body: JSON.stringify({
                'username': this.state.username,
                'password': this.state.password
            })
        };
        const { username, password } = this.state;

        if (username && password) {
            fetch(apiBaseUrl + 'login', payload)
                .then((response) => {
                    if (response.status === 200) {
                        alert("Logged In! You'll be redirected on Home")
                        return response.json()
                    } else {
                        return alert("wrong pass")
                    }
                }).then((data) => {
                    this.setState({
                        accessToken: data.accestToken,
                        authenticated: data.authenticated
                    });
                    localStorage.setItem('accessToken', data.accessToken);
                    if (data.authenticated === true) {
                        console.log(this.props)
                        this.props.onLoginSuccess(data)
                    }

                })
                .catch((err) => console.log(err));
        } else {
            alert("Cannot be Empty")
        }
    }

    render() {
        return (
            <div>
                <div className="form">
                    <div>
                        <div className="form-input">
                            <div >
                                <div className="userData">
                                    <span>
                                        <img
                                            src={UserIcon}
                                        />
                                    </span>
                                    <input
                                        autocomplete="off"
                                        type="text"
                                        name="username"
                                        placeholder="Username"
                                        value={this.state.username}
                                        onChange={this.handleChangeUsername}
                                    />
                                </div>
                                <div className="userData">
                                    <span>
                                        <img
                                            src={PasswordIcon}
                                        />
                                    </span>
                                    <input
                                        autocomplete="off"
                                        type="password"
                                        name="password"
                                        placeholder="Password"
                                        value={this.state.password}
                                        onChange={this.handleChangePassword}
                                    />
                                    <p style={(this.state.username && this.state.password) ? { display: 'none' } : { display: 'block' }}> Must fill all the form!</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="form-footer">
                    <img
                        src={Btn}
                        onClick={(event) => this.handleClick(event)}
                    />
                </div>
            </div>
        );
    }
}

标签: javascriptreactjsreact-routerreact-router-dom

解决方案


如果你使用React Router,你可以使用Redirect组件:

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

export default function PrivateRoute () {
  if (notLoggedIn()) {
    return <Redirect to="/login"/>;
  }
  // return your component
}

但是如果你不在渲染函数中(即你在提交回调中)或者你想重写浏览器历史,请使用useHistory钩子(注意:钩子只在函数组件中起作用,而不是在类组件中)

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


const history = useHistory();

// After your login action you can redirect with this command:
history.push('/otherRoute');


推荐阅读