如何使用react-router-dom创建一个受保护的路由,并将响应存储在本地存储中,以便用户下次尝试打开时可以再次查看其详细信息。登录后,他们应该重定向到 Jmeter 板页面。
所有功能都添加在ContextApi中。代码和框链接:Code
我尝试过,但无法实现
路由页面
import React, { useContext } from "react";
import { globalC } from "./context";
import { Route, Switch, BrowserRouter } from "react-router-dom";
import About from "./About";
import Dashboard from "./Dashboard";
import Login from "./Login";
import PageNotFound from "./PageNotFound";
function Routes() {
const { authLogin } = useContext(globalC);
console.log("authLogin", authLogin);
return (
<BrowserRouter>
<Switch>
{authLogin ? (
<>
<Route path="/dashboard" component={Dashboard} exact />
<Route exact path="/About" component={About} />
</>
) : (
<Route path="/" component={Login} exact />
)}
<Route component={PageNotFound} />
</Switch>
</BrowserRouter>
);
}
export default Routes;
上下文页
import React, { Component, createContext } from "react";
import axios from "axios";
export const globalC = createContext();
export class Gprov extends Component {
state = {
authLogin: null,
authLoginerror: null
};
componentDidMount() {
var localData = JSON.parse(localStorage.getItem("loginDetail"));
if (localData) {
this.setState({
authLogin: localData
});
}
}
loginData = async () => {
let payload = {
token: "ctz43XoULrgv_0p1pvq7tA",
data: {
name: "nameFirst",
email: "internetEmail",
phone: "phoneHome",
_repeat: 300
}
};
await axios
.post(`https://app.fakejson.com/q`, payload)
.then((res) => {
if (res.status === 200) {
this.setState({
authLogin: res.data
});
localStorage.setItem("loginDetail", JSON.stringify(res.data));
}
})
.catch((err) =>
this.setState({
authLoginerror: err
})
);
};
render() {
// console.log(localStorage.getItem("loginDetail"));
return (
<globalC.Provider
value={{
...this.state,
loginData: this.loginData
}}
>
{this.props.children}
</globalC.Provider>
);
}
}
5条答案
按热度按时间ehxuflar1#
Issue
The
Switch
doesn't handle rendering anything other thanRoute
andRedirect
components. If you want to "nest" like this then you need to wrap each in generic routes, but that is completely unnecessary.Your login component also doesn't handle redirecting back to any "home" page or private routes that were originally being accessed.
Solution
react-router-dom
v5Create a
PrivateRoute
component that consumes your auth context.Update your
Login
component to handle redirecting back to the original route being accessed.Render all your routes in a "flat list"
react-router-dom
v6In version 6 custom route components have fallen out of favor, the preferred method is to use an auth layout component.
...
or
...
gpfsuwkq2#
对于v6:
文件链接:https://gist.github.com/mjackson/d54b40a094277b7afdd6b81f51a0393f
piok6c0g3#
希望添加突出显示永远不要忘记给予路径作为道具ProtectedRoute,否则它将无法工作。
mrfwxfqh4#
下面是一个简单的react-router v6保护的路由。我已经把所有我想保护的路由放在a routes.js 中:-
要渲染路线,只需按如下方式Map它们:-
ddarikpa5#
如果你想要一个简单的方法来实现,那么使用App.js中的Login,如果用户登录,那么设置用户变量。如果设置了用户变量,那么启动那些路径,否则它将停留在登录页面。我在我的项目中实现了这个。
)