将单个认证文件分成多个文件,现在没有显示登录按钮 [英] separating single authentication file into multiple files in react , now no display of login button

查看:78
本文介绍了将单个认证文件分成多个文件,现在没有显示登录按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反应路由器身份验证示例中学习,我已将单个文件代码到单独的文件中,但现在从未看到登录页面。
甚至没有受保护页面的文字

Learning from react router authentication example, I have split the single file code into separate files but now never seeing the login page. even no text for protected page

在登陆页面上,有3个链接

- 首页

- 公开

- 受保护

On landing page, there are 3 links
- Home
- Public
- Protected

但是当我点击受保护链接网址更改为 / login时但机器人显示任何文本或登录按钮,如示例

but when I click on Protected Link URL changes to /login but bot displaying any text or login button like in the example

而不是在控制台中收到错误

instead getting an error in console


login无法加载资源:服务器响应状态为404(未找到)。 ...登录

login Failed to load resource: the server responded with a status of 404 (Not Found). ... login

这里是相关代码

  import React from 'react'

  import { Route, Redirect } from 'react-router-dom'

  import { fakeAuth } from './fakeAuth'

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



fakeAuth.js



fakeAuth.js

    export const fakeAuth = {
      isAuthenticated: false,
      authenticate(cb) {
        console.log('is authenticated');
        this.isAuthenticated = true
        setTimeout(cb, 100) // fake async
      },
      signout(cb) {
         console.log('signout');
        this.isAuthenticated = false
        setTimeout(cb, 100)
      }
    }



AuthButton.js



AuthButton.js

    import React from 'react'
    import { withRouter } from 'react-router-dom'
    import { fakeAuth } from './fakeAuth'

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



Login.js



Login.js

  import React from 'react'

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

  import { fakeAuth } from './fakeAuth'


  class Login extends React.Component {
    constructor(props) {
      super(props);
      this.state = { redirectToReferrer: false };
    }

    login() {
      fakeAuth.authenticate(() => {
        this.setState({ redirectToReferrer: true })
      })
    }

    render() {
      const { from } = this.props.location.state || { from: { pathname: '/' } }
      const { redirectToReferrer } = this.state
      console.log("redirectToReferrer", redirectToReferrer);

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

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

  export default Login



index.jsx



index.jsx

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'

    import { BrowserRouter, Route, Link } from 'react-router-dom'

    import { AuthButton } from './AuthButton'

    import { Login } from './Login'

    import { PrivateRoute } from './PrivateRoute'

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

    ReactDOM.render(
        <BrowserRouter>
        <div>
        <App />
        <AuthButton />
          <ul>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/public">Public Page</Link></li>
            <li><Link to="/protected">Protected Page</Link></li>
          </ul>
          <hr/>
          <Route path="/public" component={Public} />
          <Route path="/login" component={Login} />
          <PrivateRoute path="/protected" component={Protected} />
        </div>
        </BrowserRouter>,
      document.getElementById('root')
  );



App.js



App.js

    import React, { Component } from 'react';
    import logo from '../logo.svg';
    import '../App.css';

    class App extends Component {
      render() {
        return (
          <div className="App">
            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <h1 className="App-title">Welcome to React</h1>
            </header>
          </div>
        );
      }
    }

    export default App;

我怀疑是 Login.js 中的错误,因为这是一个类组件,但无法弄清楚我错过了什么。请帮助

My suspect is the mistake in Login.js as this is a class component but could not figure out what am I missing. Please help

推荐答案

主要问题是您将Login导出为默认导出并将其导入为命名导入。在index.jsx中更改:

The main problem is that you are exporting Login as a default export and importing it as a named import. In index.jsx change:

import {Login} from './Login'

import Login from './Login'

这仍然无效,因为还有第二个错误,这个里面的登录()登录中是不正确的,这可以解决通过在构造函数中将函数绑定到正确的this。在Login.js中使用:

This will still not work as there is a second bug, the this inside login() in Login is not the correct one, this can be solved by binding the function to the correct this in the constructor. In Login.js use this:

constructor(props) {
  super(props);
  this.state = { redirectToReferrer: false };
  this.login = this.login.bind(this); // Fix |this| inside login()
}

这篇关于将单个认证文件分成多个文件,现在没有显示登录按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆