繁体   English   中英

分解成组件后,登录表单React无法正常工作

[英]Login form React doesn't work when broken into components

作为一个新手Reacteur,我一直在遵循本教程来使用reactjs构建一个简单的登录表单。 一切正常,并按预期工作。 整个教程基于一个signle脚本。

这是最终代码(来自审讯):

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>
  )
}

但是,问题是当我尝试将不同的脚本放入不同的文件并导入它们时。 从上面的代码中,我将以下代码移动到名为Authenticator.js的脚本中,如下所示:

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 }
        }} />
  )} />
)

并将其导入到原始文件中为:

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

我还将Login类作为组件移至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

并将其导入脚本中:

import Login from './login/Login'

当然,我从教程的脚本中删除了这些方法。 理想情况下,现在当我进入/protected链接而不登录时,应该将我重定向到登录页面。 但是,我什么也看不到。 但是,我可以访问/login页面,并且登录按预期进行。 我相信问题出在Authenticator类上,但是除了将代码移到另一个文件之外,我没有做任何其他更改。

这是我最后的更改的主要脚本:

// 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;

有人可以帮忙吗? 提前致谢。

看来您在身份验证器文件中导入错误。 您正在导入BrowserRouter而不是Route

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

这应该是

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

暂无
暂无

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

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