【问题标题】:How to save the user's authorization in session in react?如何在反应中保存用户在会话中的授权?
【发布时间】:2025-12-21 16:45:06
【问题描述】:

当重新加载 web 应用程序时,应用程序再次将我们引导到主页,我们需要再次登录。下面是为路由编写的代码和应用程​​序本身的代码。

文件“AppRout”中的代码

const AppRouter = () => {

    const {isAuth} = useContext(AuthContext);
    return (
        isAuth
            ?
            <Routes>
                <Route path="*" element={<MainPage/>}/>
                <Route exact path="/catalog" element={<Catalog/>}/>
                <Route exact path="/catalog/:id" element={<Booking/>}/>
                <Route exact path="/account" element={<Account/>}/>
            </Routes>
            :
            <Routes>
                <Route path="*" element={<MainPage/>}/>
                <Route exact path="/login" element={<LogIn/>}/>
                <Route exact path="/registration" element={<Registration/>}/>
            </Routes>

    );
};

文件“App”中的代码

function App() {
    const [isAuth, setIsAuth] = useState(false);

    return (
        <AuthContext.Provider value={{
            isAuth,
            setIsAuth
        }}>
            <BrowserRouter>
                <AppRouter/>
            </BrowserRouter>
        </AuthContext.Provider>

    );
};

请告诉我如何解决这个问题。

【问题讨论】:

  • 您是否使用 cookie、JWT 或其他方式进行身份验证?

标签: reactjs session routes save


【解决方案1】:

如果您打算使用 JWT,那么无论用户是否通过身份验证,您都可以使用本地存储来持久化。

例如:执行 api 调用后

    const handleSubmit = async e => {
  e.preventDefault();
  const user = { username, password };
  // send the username and password to the server
  const response = await axios.post(
    "http://your-api/api/login",
    user
  );
  // set the state of the user
  setUser(response.data)
  // store the user in localStorage
  localStorage.setItem('user', response.data)
  console.log(response.data)
};

你可以像这样得到用户:

 useEffect(() => {
    const loggedInUser = localStorage.getItem("user");
    if (loggedInUser) {
      const foundUser = JSON.parse(loggedInUser);
      setUser(foundUser);
    }
  }, []);

【讨论】:

  • 这样不会被黑客入侵吗?