- 首页
- 前端开发
- 成功登录后,this.props.history.push 不会进入新页面,因为 ProtectedRoute 不成功
成功登录后,this.props.history.push 不会进入新页面,因为 ProtectedRoute 不成功
[英] On successful login, this.props.history.push does not take to new page as ProtectedRoute is not successful
本文介绍了成功登录后,this.props.history.push 不会进入新页面,因为 ProtectedRoute 不成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在收到 200 状态代码后,我尝试转到仪表板页面.但是,它不能按预期工作.我正在使用 React Context 和 ProtectedRoute.当我得到成功的响应时,我调用 login()
函数,它使 isAuthenticated
为真,但仍然没有将我带到仪表板页面.
PS:我检查并看到在我的受保护路线中,它转到第二部分并被重定向到/",因此我在同一页面上.不知道为什么会这样
登录
import { AuthContext } from './AuthContext'异步处理提交(事件){//我在此之前发送请求const status = await res.statusconst json = 等待 res.json();如果(状态 === 200){const {登录} = this.context;登录();this.props.history.push('/dashBoard')console.log('完成')} 别的 {console.log('未完成')}} 捕捉(错误){console.log('错误', 错误)}}静态上下文类型 = AuthContext;使成为() {返回 (<Container className="formlogin"><div><Form className = "signinform backg-sheet1" onSubmit={this.handleSubmit}><div><h3 style = {{color: 'white', textAlign: 'center'}}>登录 </h3><Form.Group controlId = "formBasicUsername"><Form.Label style = {{color: 'white'}}>用户名</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'}}>密码</Form.Label><Form.Control required name = "password" type = "password" placeholder = "Enter password" onChange = {this.handleChange}/></Form.Group><div style={{textAlign: 'center'}}><按钮变体=警告"类型=提交">提交</按钮>
</表格>
</容器>);}}导出默认 withRouter(SignIn);
App.js
class App 扩展 React.Component {构造函数(道具){超级(道具);}使成为() {返回 (<div><路由器><AuthProvider><导航栏/><开关><路由精确路径 = '/'组件 = {LandingPage}/><路由精确路径 = '/register'组件 = {注册}/><ProtectedRoute 精确路径 = '/dashBoard'组件 = {仪表板}/></开关></AuthProvider></路由器>
);}}导出默认应用程序;
身份验证提供者
import React, { Component} from 'react';export const AuthContext = React.createContext();类 AuthProvider 扩展组件 {状态 = {isAuthenticated: 假}构造函数(){极好的()this.login = this.login.bind(this)this.logout = this.logout.bind(this)}登录() {setTimeout(() => this.setState({ isAuthenticated: true }), 1000)}登出() {this.setState({ isAuthenticated: false })}使成为() {console.log(this.state.isAuthenticated)返回(<AuthContext.Provider value={{isAuthenticated: this.state.isAuthenticated, login: this.login, logout: this.logout}}>{this.props.children}</AuthContext.Provider>)}}const AuthConsumer = AuthContext.Consumer出口 { AuthProvider, AuthConsumer }
受保护的路线
从 'react' 导入 React从'react-router-dom'导入{路由,重定向}从 './AuthContext' 导入 { AuthConsumer }const ProtectedRoute = ({component: Component, ...rest}) =>(<认证消费者>{({ isAuthenticated }) =>(<路线渲染={(道具)=>isAuthenticated?:<重定向到=/"/>}{...休息}/>)}</AuthConsumer>)导出默认的 ProtectedRoute
登陆页面
从'react'导入React;从'./SignIn'导入登录从 './NavigationBar' 导入 NavigationBar从'react-bootstrap'导入{行};导入'./Styles.css'class LandingPage 扩展了 React.Component {构造函数(道具){超级(道具);}使成为() {返回 (<div><div className = "backg"><div className = "backg-sheet"><登录/>
)}}导出默认登陆页面
解决方案
做一些更正,您将成功导航到仪表板页面.
- 您的 handleSubmit 是一个普通函数,您正在丢失
this
的上下文.所以让它成为一个箭头函数 - 使用 event.preventDefault 否则浏览器将重新加载,您最终会返回到
/
页面.
我已将您的代码放入沙箱并使其正常工作.
代码片段
handleSubmit = async event =>{尝试 {event.preventDefault();//我在此之前发送请求//console.log("this.context", this.context);//<---- 打印成功常量状态 = 200;//等待 res.status;//const json = await res.json();如果(状态 === 200){const { 登录 } = this.context;等待登录();console.log("this.context", this.context);this.props.history.push("/dashBoard");console.log("完成");} 别的 {console.log("未完成");}} 捕捉(错误){console.log("错误", 错误);}};
After I receive a 200 status code, I try to go to the dashboard page. However, it does not work as intended. I am using React Context and ProtectedRoute. When I get the successful response, I call the login()
function and it makes isAuthenticated
as true but still does not take me to the dashboard Page.
PS: I checked and saw that in my protected route, it goes to the second part and gets redirected to "/" and hence I am on the same page. Do not know why that is happening
Signin
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);
App.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;
AuthProvider
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 }
ProtectedRoute
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
LandingPage
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
解决方案
Make few corrections and you will successfully get navigated to dashboard page.
- Your handleSubmit is a normal function and you are losing the context of
this
. So make it an arrow function
- Use event.preventDefault else browser will reload and you end up back to
/
page.
I have placed your code in the sandbox and made it work.
Code snippet
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);
}
};
这篇关于成功登录后,this.props.history.push 不会进入新页面,因为 ProtectedRoute 不成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文