在 ReactJS 中重定向到上一页 [英] Redirect To Previous Page in ReactJS
问题描述
由于我检查了 isLoggedIn
,因此在重定向到上一页时遇到问题.现在的问题是在检查 isLoggedIn
之后它重定向到默认路由.我如何维护我所在的页面?我现在所做的是使用 referer
但它是未定义的.请帮我找到另一种方法.请在下面检查我的代码:
Login.js
const Form = (props) =>{const 类 = useStyles();const isLoggedIn = useSelector((state) => state.auth.isLoggedIn);constreferer = props.referer;const 历史 = useHistory();控制台日志(历史);const { values, touch, errors, isSubmitting, handleChange, handleBlur, handleSubmit } = props;如果(已登录){return <Redirect to={referer}/>;}返回 (<div className={classes.root}><网格容器方向="row" justify="center"><网格项lg={4} md={5} xs={10}><卡片><form onSubmit={handleSubmit}><卡片头标题=登录"类={{标题:classes.cardHeader,}}className={classes.cardHeader}/><CardContent className={classes.textFieldSection}><文本字段全屏宽度标签=用户名"名称=用户名"类型=文本"变体=概述"值={values.username}onChange={handleChange}onBlur={handleBlur}helperText={touched.username ?错误.用户名:''}错误={touched.username &&布尔值(错误.用户名)}输入道具={{尾饰:(<输入装饰><AccountCircle/></InputAdornment>),}}/><文本字段全屏宽度标签=密码"名称=密码"style={{ marginTop: '1rem' }}类型=密码"变体=概述"值={values.password}onChange={handleChange}onBlur={handleBlur}helperText={touched.password ?错误密码:''}错误={touched.password &&布尔值(错误.密码)}输入道具={{尾饰:(<输入装饰><锁定图标/></InputAdornment>),}}/></卡片内容><CardActions className={classes.loginButtonSection}><按钮类型=提交"颜色=主要"变体=包含"className={classes.loginButton}禁用={isSubmitting}>登录</按钮></CardActions></表单></卡片></网格></网格>
);};让 yup = require('yup');export const Login = (props) =>{const dispatch = useDispatch();const MyFormWithFormik = withFormik({mapPropsToValues: ({用户名,密码}) =>{返回 {用户名:用户名 ||'',密码:密码 ||'',};},验证架构:yup.object().shape({用户名:yup.string().required('输入你的用户名'),密码:yup.string().required('输入密码'),}),handleSubmit: (values, { setSubmitting }) =>{调度(登录(值.用户名,值.密码));设置提交(假);},})(形式);返回 <MyFormWithFormik/>;};Form.propTypes = {类名:PropTypes.string,};导出默认登录;
PrivateRoute.js
从'react'导入React;从'react-router-dom'导入{路由,重定向};从 'axios' 导入 axios;从'react-redux'导入{useSelector};函数 PrivateRoute({ 组件: 组件, ...rest }) {const authTokens = useSelector((state) => state.auth.access_token);函数 checkTokenExpiry() {如果(身份验证令牌){axios.interceptors.request.use(功能(配置){const token = `Bearer ${authTokens}`;config.headers.Authorization = 令牌;控制台日志(配置);返回配置;},(错误) =>{控制台日志(错误);Promise.reject(error);});}}如果(authTokens != null){checkTokenExpiry();}返回 (<路线{...休息}渲染={(道具)=>身份验证令牌?(<组件{...道具}/>) : (<重定向到={{ pathname: '/login', state: { referer: props.location } }}/>)}/>);}导出默认的 PrivateRoute;
PrivateAdminOnlyRoute
从'react'导入React;从'react-router-dom'导入{路由,重定向};从 'axios' 导入 axios;从'react-redux'导入{useSelector};功能 PrivateAdminOnlyRoute({ 组件: 组件, ...rest }) {const authTokens = useSelector((state) => state.auth.access_token);const isAdmin = useSelector((state) => state.auth.is_admin);函数 checkTokenExpiry() {如果(身份验证令牌){axios.interceptors.request.use(功能(配置){const token = `Bearer ${authTokens}`;config.headers.Authorization = 令牌;控制台日志(配置);返回配置;},(错误) =>{控制台日志(错误);Promise.reject(error);});}}如果(authTokens != null){checkTokenExpiry();}返回 (<路线{...休息}渲染={(道具)=>authTokens &&isAdmin === 真?(<组件{...道具}/>) : authTokens &&(isAdmin === false || undefined || null) ?(<重定向到={{ pathname: '/pending', state: { referer: props.location } }}/>) : (<重定向到={{ pathname: '/login', state: { referer: props.location } }}/>)}/>);}导出默认 PrivateAdminOnlyRoute;
Routes.js
import React, { useState } from 'react';import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom';从 './PrivateRoute' 导入 PrivateRoute;从'./pages/Login/Login'导入登录;从'./pages/Signup/Signup'导入注册;从'./pages/Common'导入Common;功能路线(){返回 (<路由器><开关><Route path="/login" component={Login}/><Route path="/signup" component={Signup}/><PrivateRoute path="/" component={Common}/></开关></路由器>);}导出默认路由;
Using state
inside Redirect
不是将 state
assigan 到 >props
但要location
import { useLocation } from 'react-router-dom';const location = useLocation();const referer = location.state &&location.state.referer
<小时>
关于您的代码的另一件事(不直接连接到您的问题)是
(isAdmin === false || undefined || null)
isAdmin
仅与 false
进行比较,如果 isAdmin
不是 false
,则不会进行比较undefined
,但 undefined
独立存在(具有虚假行为...),对于 null
希望对你有帮助:)
I have a problem on redirect to the previous page since i do a check isLoggedIn
. The problem right now is after check isLoggedIn
it redirect to the default route. How do i maintain the page where I'm into?
What i did right now is using the referer
but it is undefined. Pls help me find another way.
Pls check my code below:
Login.js
const Form = (props) => {
const classes = useStyles();
const isLoggedIn = useSelector((state) => state.auth.isLoggedIn);
const referer = props.referer;
const history = useHistory();
console.log(history);
const { values, touched, errors, isSubmitting, handleChange, handleBlur, handleSubmit } = props;
if (isLoggedIn) {
return <Redirect to={referer} />;
}
return (
<div className={classes.root}>
<Grid container direction="row" justify="center">
<Grid item lg={4} md={5} xs={10}>
<Card>
<form onSubmit={handleSubmit}>
<CardHeader
title="LOGIN"
classes={{
title: classes.cardHeader,
}}
className={classes.cardHeader}
/>
<CardContent className={classes.textFieldSection}>
<TextField
fullWidth
label="Username"
name="username"
type="text"
variant="outlined"
value={values.username}
onChange={handleChange}
onBlur={handleBlur}
helperText={touched.username ? errors.username : ''}
error={touched.username && Boolean(errors.username)}
InputProps={{
endAdornment: (
<InputAdornment>
<AccountCircle />
</InputAdornment>
),
}}
/>
<TextField
fullWidth
label="Password"
name="password"
style={{ marginTop: '1rem' }}
type="password"
variant="outlined"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
helperText={touched.password ? errors.password : ''}
error={touched.password && Boolean(errors.password)}
InputProps={{
endAdornment: (
<InputAdornment>
<LockIcon />
</InputAdornment>
),
}}
/>
</CardContent>
<CardActions className={classes.loginButtonSection}>
<Button
type="submit"
color="primary"
variant="contained"
className={classes.loginButton}
disabled={isSubmitting}
>
Log In
</Button>
</CardActions>
</form>
</Card>
</Grid>
</Grid>
</div>
);
};
let yup = require('yup');
export const Login = (props) => {
const dispatch = useDispatch();
const MyFormWithFormik = withFormik({
mapPropsToValues: ({ username, password }) => {
return {
username: username || '',
password: password || '',
};
},
validationSchema: yup.object().shape({
username: yup.string().required('Enter your username'),
password: yup.string().required('Enter your password'),
}),
handleSubmit: (values, { setSubmitting }) => {
dispatch(login(values.username, values.password));
setSubmitting(false);
},
})(Form);
return <MyFormWithFormik />;
};
Form.propTypes = {
className: PropTypes.string,
};
export default Login;
PrivateRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import axios from 'axios';
import { useSelector } from 'react-redux';
function PrivateRoute({ component: Component, ...rest }) {
const authTokens = useSelector((state) => state.auth.access_token);
function checkTokenExpiry() {
if (authTokens) {
axios.interceptors.request.use(
function (config) {
const token = `Bearer ${authTokens}`;
config.headers.Authorization = token;
console.log(config);
return config;
},
(error) => {
console.log(error);
Promise.reject(error);
}
);
}
}
if (authTokens != null) {
checkTokenExpiry();
}
return (
<Route
{...rest}
render={(props) =>
authTokens ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { referer: props.location } }} />
)
}
/>
);
}
export default PrivateRoute;
PrivateAdminOnlyRoute
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import axios from 'axios';
import { useSelector } from 'react-redux';
function PrivateAdminOnlyRoute({ component: Component, ...rest }) {
const authTokens = useSelector((state) => state.auth.access_token);
const isAdmin = useSelector((state) => state.auth.is_admin);
function checkTokenExpiry() {
if (authTokens) {
axios.interceptors.request.use(
function (config) {
const token = `Bearer ${authTokens}`;
config.headers.Authorization = token;
console.log(config);
return config;
},
(error) => {
console.log(error);
Promise.reject(error);
}
);
}
}
if (authTokens != null) {
checkTokenExpiry();
}
return (
<Route
{...rest}
render={(props) =>
authTokens && isAdmin === true ? (
<Component {...props} />
) : authTokens && (isAdmin === false || undefined || null) ? (
<Redirect to={{ pathname: '/pending', state: { referer: props.location } }} />
) : (
<Redirect to={{ pathname: '/login', state: { referer: props.location } }} />
)
}
/>
);
}
export default PrivateAdminOnlyRoute;
Routes.js
import React, { useState } from 'react';
import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom';
import PrivateRoute from './PrivateRoute';
import Login from './pages/Login/Login';
import Signup from './pages/Signup/Signup';
import Common from './pages/Common';
function Routes() {
return (
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/signup" component={Signup} />
<PrivateRoute path="/" component={Common} />
</Switch>
</Router>
);
}
export default Routes;
Using state
inside Redirect
isn't assigan state
to props
but to location
import { useLocation } from 'react-router-dom';
const location = useLocation();
const referer = location.state && location.state.referer
another thing about your code (that not connect directly to your issue) is
(isAdmin === false || undefined || null)
isAdmin
compared just to false
, and in case isAdmin
isn't false
it is not being compared to undefined
, but undefined
stand by itself (with falsy behavior...), and so goes for null
hope it's helpful :)
这篇关于在 ReactJS 中重定向到上一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!