繁体   English   中英

成功登录后, this.props.history.push 不会进入新页面,因为 ProtectedRoute 不成功

[英]On successful login, this.props.history.push does not take to new page as ProtectedRoute is not successful

在收到 200 状态码后,我尝试将 go 转到仪表板页面。 但是,它不能按预期工作。 我正在使用 React Context 和 ProtectedRoute。 当我得到成功的响应时,我调用login() function 并且它使isAuthenticated为真,但仍然没有将我带到仪表板页面。

PS:我检查并看到在我的受保护路线中,它进入第二部分并被重定向到“/”,因此我在同一页面上。 不知道为什么会这样

登入

import { AuthContext } from './AuthContext'

async handleSubmit(event) {

        //I send the request before this

            const status = await res.status
            const json = await res.json();
            if(status === 200) {
                const {login} = this.context;
                login();
                this.props.history.push('/dashBoard')
                console.log('done')
            } else {
                console.log('not done')
            }
        } catch (error) {
            console.log('Error', error)
        }
    }
static contextType = AuthContext;

render() {
return ( 
<Container className="formlogin">
                <div>
                    <Form className = "signinform backg-sheet1" onSubmit={this.handleSubmit}>
                        <div>
                            <h3 style = {{color: 'white', textAlign: 'center'}}> SIGN IN </h3>
                            <Form.Group controlId = "formBasicUsername">
                                <Form.Label style = {{color: 'white'}}>Username</Form.Label>
                                <Form.Control required name = "username" type = "text" placeholder = "Enter username" onChange = {this.handleChange}/>
                            </Form.Group>


                            <Form.Group controlId = "formBasicPassword">
                                <Form.Label style = {{color: 'white'}}>Password</Form.Label>
                                <Form.Control required name = "password" type = "password" placeholder = "Enter password" onChange = {this.handleChange}/>
                            </Form.Group>


                            <div style={{textAlign: 'center'}}>
                                <Button variant="warning" type="submit">
                                    Submit
                                </Button>
                            </div>  
                        </div>
                    </Form>
                </div>
            </Container>
        );
    }
}

export default withRouter(SignIn);

应用程序.js

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() { 
  return (
    <div>
      <Router>
          <AuthProvider>
            <NavigationBar />
            <Switch>
              <Route exact path = '/'
                component = {LandingPage}
              />
              <Route exact path = '/register'
                component = {Register}
              />
              <ProtectedRoute exact path = '/dashBoard' 
                component = {dashBoard}
              />
            </Switch>
          </AuthProvider>
      </Router>
    </div>
  );
}
}

export default App;

身份验证提供者

import React, { Component} from 'react';

export const AuthContext = React.createContext();

class AuthProvider extends Component {
    state = {
        isAuthenticated: false
    }

    constructor() {
        super()
        this.login = this.login.bind(this)
        this.logout = this.logout.bind(this)
    }

    login() {
        setTimeout(() => this.setState({ isAuthenticated: true }), 1000)
    }

    logout() {
        this.setState({ isAuthenticated: false })
    }

    render() {
        console.log(this.state.isAuthenticated)
        return(
            <AuthContext.Provider value={{isAuthenticated: this.state.isAuthenticated, login: this.login, logout: this.logout}}>
            {this.props.children}
            </AuthContext.Provider>
        )
    }
}

const AuthConsumer = AuthContext.Consumer


export { AuthProvider, AuthConsumer }

受保护的路由

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { AuthConsumer } from './AuthContext'

const ProtectedRoute = ({component: Component, ...rest}) => (
        <AuthConsumer>
            {({ isAuthenticated }) => ( 
                <Route

                    render={(props) => 
                        isAuthenticated?<Component {...props} /> : <Redirect to="/" />
                    }
                    {...rest}
                />
            )}
        </AuthConsumer>
)

export default ProtectedRoute

登陆页面

import React from 'react';
import SignIn from './SignIn'
import NavigationBar from './NavigationBar'
import {Row} from 'react-bootstrap';
import './Styles.css'

class LandingPage extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                    <div className = "backg">
                        <div className = "backg-sheet">
                            <SignIn />
                        </div>
                    </div>
            </div>
        )
    }

}

export default LandingPage

进行一些更正,您将成功导航到仪表板页面。

  1. 您的 handleSubmit 是正常的 function ,您正在失去this的上下文。 所以让它成为一个箭头 function
  2. 使用 event.preventDefault 否则浏览器将重新加载,你最终回到/页面。

我已将您的代码放入沙箱并使其正常工作。

编辑路由器身份验证问题修复

代码片段

handleSubmit = async event => {
    try {
      event.preventDefault();
      //I send the request before this
      // console.log("this.context", this.context); //<---- prints successfully

      const status = 200; //await res.status;
      // const json = await res.json();
      if (status === 200) {
        const { login } = this.context;
        await login();
        console.log("this.context", this.context);
        this.props.history.push("/dashBoard");
        console.log("done");
      } else {
        console.log("not done");
      }
    } catch (error) {
      console.log("Error", error);
    }
  };

您需要实现 withRouter 组件才能访问 this.props.hostory... 变量,如下所示。

import { withRouter } from 'react-router'; 


export default withRouter(Login);

暂无
暂无

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

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