Creating protected routes: a how-to guide using react-router-dom
P粉596191963
2023-08-24 11:22:28
<p>How to use <code>react-router-dom</code> to create a protected route and store the response in localStorage so the user can view their details again the next time they open it. After logging in, they should be redirected to the dashboard page. </p>
<p>All functions are added in ContextApi.Codesandbox链接:Code</p>
<p>我尝试过,但无法实现</p>
<p>路由页面</p>
<pre class="brush:php;toolbar:false;">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;</pre>
<p>上下文页面</p>
<pre class="brush:php;toolbar:false;">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>
);
}
}</pre>
<p><br /></p>
For v6:
Documentation link: https://gist.github.com/mjackson/d54b40a094277b7afdd6b81f51a0393f
question
Switch
No rendering will be handled except for theRoute
andRedirect
components. If you wanted to "nest" like this, then you would need to wrap each component in a generic route, but this is completely unnecessary.Your login component has not yet handled redirecting back to the original visited "home" or private route.
solution
react-router-dom
v6In version 6, custom routing components are no longer popular, and the preferred method is to use auth layout components.
...
or
...
react-router-dom
v5Create a
PrivateRoute
component that consumes your auth context.Update your
Login
component to handle redirects back to the original access route.Render all routes as a "flat list"