[英]How redirect user if error.status == 401?
My goal is to redirect users if the code of request is equal to 401. I wrote follow code but it display me error 401. It displays me 401 (from console.log but below error).我的目标是在请求代码等于 401 时重定向用户。我编写了以下代码,但它显示错误 401。它显示 401(来自 console.log 但低于错误)。 How can I implement redirection, if the error is equal to 401?如果错误等于 401,我如何实现重定向?
import axiosConfig from "../../config/axios";
import actions from "./actions";
import { Redirect } from "react-router";
const fetchUser = async () => {
const response = await axiosConfig.get('api/get-user')
.catch(function (error) {
console.log(error.response.status) // 401
console.log(error.response.data.error) //Please Authenticate or whatever returned from server
if (error.response.status == 401) {
return(
<Redirect
to={{
pathname: '/login',
state: { from: location },
}}
/>
);
}
});
return response.data
}
export const getUser = () =>
async (dispatch) => {
const user = await fetchUser()
dispatch(actions.setUser(user));
}
@Update Routing setup @Update 路由设置
const Container = () => {
return (
<div className="container">
<Router>
<Switch>
<Route path="/login">
<Login />
</Route>
<Route path="/register">
<Login />
</Route>
<Route path="/all-users">
<Alltasks />
</Route>
<Route path="/all-articles">
<AllUsers />
</Route>
</Switch>
</Router>
<ToastContainer />
</div>
);
}
You can't return a Redirect
component from an action, utility, or callback like this and expect it to be rendered and effect a redirect to a new route.您不能像这样从操作、实用程序或回调返回Redirect
组件,并期望它被渲染并实现到新路由的重定向。 Your option is to access the history
object and invoke an imperative redirect.您的选择是访问history
object 并调用命令式重定向。
Connect your router to redux with connected-react-router .使用connected-react-router将您的路由器连接到 redux。 The basic gist is to create a custom "createRootReducer" function, create a history
object, use the "ConnectedRouter" component.基本要点是创建自定义“createRootReducer”function,创建history
object,使用“ConnectedRouter”组件。 This allows you to dispatch redux actions to effect navigation actions in your app.这允许您分派 redux 操作来影响应用程序中的导航操作。
Follow the steps to setup and connect routing to your redux store.按照步骤设置路由并将其连接到您的 redux 商店。
To use in your asynchronous action:在您的异步操作中使用:
import { replace } from 'connected-react-router';
...
const fetchUser = async () => {
try {
const response = await axiosConfig.get('api/get-user');
return response.data;
} catch (error) {
if (error.response.status == 401) {
throw new Error(error);
}
}
}
export const getUser = () => async (dispatch) => {
try {
const user = await fetchUser();
dispatch(actions.setUser(user));
} catch {
dispatch(replace('/login'));
}
}
Create a history object and import and use in getUser
action.创建历史记录 object 并在getUser
操作中导入和使用。
Create a memory, hash, or browser history object:创建memory、hash,或者浏览器历史记录object:
import { createBrowserHistory } from 'history';
export const history = new createBrowserHistory();
Import the plain Router
from react-router
and pass the history object as prop:从react-router
导入普通Router
并将历史记录 object 作为 prop 传递:
import { Router } from 'react-router';
import { history } from '../path/to/custom/history';
...
<Router history={history}>
...
</Router>
Import and use history
in the getUser
action:在getUser
操作中导入和使用history
:
import { history } from '../path/to/custom/history';
...
const fetchUser = async () => {
try {
const response = await axiosConfig.get('api/get-user');
return response.data;
} catch (error) {
if (error.response.status == 401) {
throw new Error(error);
}
}
}
export const getUser = () => async (dispatch) => {
try {
const user = await fetchUser();
dispatch(actions.setUser(user));
} catch {
history.replace('/login');
}
}
Pass the history
object to the getUser
action.将history
object 传递给getUser
操作。
const fetchUser = async () => {
try {
const response = await axiosConfig.get('api/get-user');
return response.data;
} catch (error) {
if (error.response.status == 401) {
throw new Error(error);
}
}
}
export const getUser = (history) => async (dispatch) => {
try {
const user = await fetchUser();
dispatch(actions.setUser(user));
} catch {
history.replace('/login');
}
}
Usage:用法:
import { useHistory } from 'react-router-dom';
...
const history = useHistory();
...
getUser(history);
...
const mapDispatchToProps = {
getUser,
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.