简体   繁体   中英

Login form React doesn't work when broken into components

As a newbie Reacteur, I have been following this tutorial to build a simple login form with reactjs. Everything works fine and it works as intended. The whole tutorial is based on a signle script.

Here is the final code (from the tutrial):

import React from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from 'react-router-dom'

const authenticator = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true
    setTimeout(cb, 100)
  },
  signout(cb) {
    this.isAuthenticated = false
    setTimeout(cb, 100)
  }
}

const Public = () => <h3>Public</h3>
const Protected = () => <h3>Protected</h3>

class Login extends React.Component {
  state = {
    redirectToReferrer: false
  }
  login = () => {
    authenticator.authenticate(() => {
      this.setState(() => ({
        redirectToReferrer: true
      }))
    })
  }
  render() {
    const { from } = this.props.location.state || { from: { pathname: '/' } }
    const { redirectToReferrer } = this.state

    if (redirectToReferrer === true) {
      return <Redirect to={from} />
    }

    return (
      <div>
        <p>You must log in to view the page</p>
        <button onClick={this.login}>Log in</button>
      </div>
    )
  }
}

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    fakeAuth.isAuthenticated === true
      ? <Component {...props} />
      : <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }} />
  )} />
)

const AuthButton = withRouter(({ history }) => (
  fakeAuth.isAuthenticated ? (
    <p>
      Welcome! <button onClick={() => {
        fakeAuth.signout(() => history.push('/'))
      }}>Sign out</button>
    </p>
  ) : (
    <p>You are not logged in.</p>
  )
))

export default function AuthExample () {
  return (
    <Router>
      <div>
        <AuthButton/>
        <ul>
          <li><Link to="/public">Public Page</Link></li>
          <li><Link to="/protected">Protected Page</Link></li>
        </ul>
        <Route path="/public" component={Public}/>
        <Route path="/login" component={Login}/>
        <PrivateRoute path='/protected' component={Protected} />
      </div>
    </Router>
  )
}

HGowever, the problem is when I try to put the different scripts in different files and import them. From the above code, I moved the following code to a script named Authenticator.js , as below:

import React from 'react'
import { BrowserRouter as Route, Redirect } from "react-router-dom";

export const authenticator = {
    isAuthenticated: false,
    authenticate(cb) {
        this.isAuthenticated = true
        setTimeout(cb, 100) // fake async
    },
    signout(cb) {
        this.isAuthenticated = false
        setTimeout(cb, 100) // fake async
    }
}

export const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    authenticator.isAuthenticated === true
      ? <Component {...props} />
      : <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }} />
  )} />
)

and imported it in the original file as :

import { PrivateRoute, authenticator } from './login/Authenticator'

I also moved the Login class as a component to Login.js :

import React, { Component } from 'react'
import { authenticator } from './Authenticator'
import { Redirect } from "react-router-dom";

class Login extends Component {
    state = {
        redirectToReferrer: false
    }
    login = () => {
        authenticator.authenticate(() => {
            this.setState(() => ({
                redirectToReferrer: true
            }))
        })
    }
    render() {
        const { from } = this.props.location.state || { from: { pathname: '/' } }
        const { redirectToReferrer } = this.state

        if (redirectToReferrer === true) {
        return <Redirect to={from} />
        }
        return (
        <div>
            <p>You must log in to view the page</p>
            <button onClick={this.login}>Log in</button>
        </div>
        )
    }
}

export default Login

And imported it in the script:

import Login from './login/Login'

And of course, I deleted these methods from the script from the tutorial. Ideally, now when, I go the /protected link, without logging in, I should be redirectd to the login page. HOwever, I do not see any thing. I can however access, the /login page and the login persists as expected. I believe the problem is with the Authenticator class, but I have not changed anything apart from moving the code to a different file.

Here is my final main script with the changes:

// import css
import 'bootstrap/dist/css/bootstrap.css'
import '@fortawesome/fontawesome-free/css/all.min.css'
import './css/ViewerApp.css'
// import js modules
import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Link, withRouter } from "react-router-dom";
import 'jquery/dist/jquery.min.js'
import 'popper.js/dist/umd/popper.min.js'
import 'bootstrap/dist/js/bootstrap.min.js'
import Login from './login/Login'
import { PrivateRoute, authenticator } from './login/Authenticator'
// import TableView from './table/TableView'

const Public = () => <h3>Public</h3>
const Protected = () => <h3>Protected</h3>

class ViewerApp extends Component {
  render() {
    return (
      <Router>
        <ul style={{ marginTop:'122px' }}>
          <li><Link to="/public">Public Page</Link></li>
          <li><Link to="/protected">Protected Page</Link></li>
        </ul>
        <AuthButton/>
        <Route path="/public" component={Public}/>
        <Route path="/login" component={Login}/>
        <PrivateRoute path='/protected' component={Protected} />
      </Router>
    )
  }
}

const AuthButton = withRouter(({ history }) => (
  authenticator.isAuthenticated ? (
    <p>
      Welcome! <button onClick={() => {
        authenticator.signout(() => history.push('/'))
      }}>Sign out</button>
    </p>
  ) : (
    <p>You are not logged in.</p>
  )
))

export default ViewerApp;

Can anyone help? Thanks in advance.

It looks like you have wrong import in your authenticator file. You are importing the BrowserRouter instead of Route

import { BrowserRouter as Route, Redirect } from "react-router-dom";

This should be

import { Route, Redirect } from "react-router-dom";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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