Reactjs useNavigate未在登录时重定向
在提交表单时,useNavigate钩子应该检测到isAuthenticated状态并重定向到“/app/dashboard”路由,但它仍保留在“/login”路由上 App.js 此处isAuthenticated被传递到路由,并根据其全局布尔值呈现相关路由Reactjs useNavigate未在登录时重定向,reactjs,redirect,react-router-dom,Reactjs,Redirect,React Router Dom,在提交表单时,useNavigate钩子应该检测到isAuthenticated状态并重定向到“/app/dashboard”路由,但它仍保留在“/login”路由上 App.js 此处isAuthenticated被传递到路由,并根据其全局布尔值呈现相关路由 import React from "react"; import jwtDecode from "jwt-decode"; // Routing import { useRoutes } fro
import React from "react";
import jwtDecode from "jwt-decode";
// Routing
import { useRoutes } from "react-router-dom";
import routes from "./routes"
const token = localStorage.FBIdToken;
let isAuthenticated;
if (token) {
const decodedToken = jwtDecode(token);
console.log(decodedToken);
// Check whether the token is expired
if (decodedToken.exp * 1000 < Date.now()) {
window.location.href = "/login";
isAuthenticated = false;
} else {
isAuthenticated = true;
}
}
function App() {
const routing = useRoutes(routes(isAuthenticated));
return (
<ThemeProvider theme={theme}>
<GlobalStyles />
{routing}
</ThemeProvider>
);
}
export default App;
我所采取的方法是肮脏的,但对于history 5.0.0版来说,它的效果却不那么好 src/utils/history.js
import { createBrowserHistory } from "history"
export default createBrowserHistory();
src/pages/auth/login.js
import React, { useState } from "react";
import { Link as RouterLink} from "react-router-dom";
import history from "../../utils/histroy";
const Login = () => {
const classes = useStyles();
const navigate = useNavigate();
const [state, setState] = useState({
email: "",
password: "",
loading: false,
errors: {},
});
const handleChange = (e) => {
// Set the value of state to corresponding input
setState({
...state,
[e.target.name]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
setState({
...state,
loading: true,
});
const userData = {
email: state.email,
password: state.password,
};
axios
.post("/login", userData)
.then((response) => {
console.log(response.data);
localStorage.setItem("FBIdToken", `Bearer ${response.data.token}`);
setState({
...state,
loading: false,
});
history.push("/app/dashboard");
histrory.go();
})
.catch((err) => {
setState({
...state,
errors: err.response.data,
loading: false,
});
});
};
return (
// Some form
);
};
export default Login;
我所采取的方法是肮脏的,但对于history 5.0.0版来说,它的效果却不那么好 src/utils/history.js
import { createBrowserHistory } from "history"
export default createBrowserHistory();
src/pages/auth/login.js
import React, { useState } from "react";
import { Link as RouterLink} from "react-router-dom";
import history from "../../utils/histroy";
const Login = () => {
const classes = useStyles();
const navigate = useNavigate();
const [state, setState] = useState({
email: "",
password: "",
loading: false,
errors: {},
});
const handleChange = (e) => {
// Set the value of state to corresponding input
setState({
...state,
[e.target.name]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
setState({
...state,
loading: true,
});
const userData = {
email: state.email,
password: state.password,
};
axios
.post("/login", userData)
.then((response) => {
console.log(response.data);
localStorage.setItem("FBIdToken", `Bearer ${response.data.token}`);
setState({
...state,
loading: false,
});
history.push("/app/dashboard");
histrory.go();
})
.catch((err) => {
setState({
...state,
errors: err.response.data,
loading: false,
});
});
};
return (
// Some form
);
};
export default Login;
useNavigate没有问题。问题是传递给我的路由的布尔参数。下面是我如何解决的 创建了一个名为src/redux/reducers/authReducer的文件
import * as actionType from "../types";
let decodedUser = localStorage.getItem("SomeToken");
// Initialize state to match auth state
const initialState = decodedUser
? { isAuthenticated: true }
: { isAuthenticated: false };
export default function (state = initialState, action) {
switch (action.type) {
case actionType.SET_AUTHENTICATED:
return {
...state,
isAuthenticated: true,
};
// Unauthenticated is in the userReducer
default:
return state;
}
}
将减速机存放在仓库中的组合减速机上
const reducers = combineReducers({
auth: authReducer,
});
然后在App.js中执行以下操作
function App() {
const { isAuthenticated } = useSelector((state) => state.auth);
const routing = useRoutes(routes(isAuthenticated));
return (
<div>Some filler code</div>
);
}
参考资料:使用导航没有问题。问题是传递给我的路由的布尔参数。下面是我如何解决的 创建了一个名为src/redux/reducers/authReducer的文件
import * as actionType from "../types";
let decodedUser = localStorage.getItem("SomeToken");
// Initialize state to match auth state
const initialState = decodedUser
? { isAuthenticated: true }
: { isAuthenticated: false };
export default function (state = initialState, action) {
switch (action.type) {
case actionType.SET_AUTHENTICATED:
return {
...state,
isAuthenticated: true,
};
// Unauthenticated is in the userReducer
default:
return state;
}
}
将减速机存放在仓库中的组合减速机上
const reducers = combineReducers({
auth: authReducer,
});
然后在App.js中执行以下操作
function App() {
const { isAuthenticated } = useSelector((state) => state.auth);
const routing = useRoutes(routes(isAuthenticated));
return (
<div>Some filler code</div>
);
}
参考: