Javascript react路由器尝试重定向用户时出现问题

Javascript react路由器尝试重定向用户时出现问题,javascript,reactjs,Javascript,Reactjs,我正在开发一个MERNG应用程序,在登录用户时遇到问题 所以,我有一个路径,它会将您带到一个页面,其中url有/profile/userId,userId由localStorage提供,因为我从那里获取该值,并且,当我注销时,我会从localStorage中删除令牌,因此,如果没有值,它应该将您带到登录页面 现在,问题是,当我登录到/profile/userId页面时,我用f5刷新页面,如果我注销,它不会让我这么做,重定向不起作用,它只在我不刷新页面时起作用,这对我的应用程序来说是个大问题,实际

我正在开发一个MERNG应用程序,在登录用户时遇到问题

所以,我有一个路径,它会将您带到一个页面,其中url有/profile/userId,userId由localStorage提供,因为我从那里获取该值,并且,当我注销时,我会从localStorage中删除令牌,因此,如果没有值,它应该将您带到登录页面

现在,问题是,当我登录到/profile/userId页面时,我用f5刷新页面,如果我注销,它不会让我这么做,重定向不起作用,它只在我不刷新页面时起作用,这对我的应用程序来说是个大问题,实际上很奇怪

也许这是我的代码有问题,我不知道如何使用重定向,所以如果你能帮我,你是最棒的

这就是代码

带有重定向的路由

import React from "react";
import "./App.css";

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect
} from "react-router-dom";

import Auth from "./website/Auth";
import SocialMedia from "./website/SocialMedia";
import SingleUser from "./website/SingleUser";

function App() {
  const logIn = JSON.parse(localStorage.getItem("token"));

  return (
    <Router>
      <Switch>
        <Route exact path="/">
          {logIn ? <Redirect to={`/profile/${logIn.data.id}`} /> : <Auth />}
        </Route>
        <Route exact path="/socialmedia" component={SocialMedia} />
        <Route exact path="/profile/:id" component={SingleUser} />
      </Switch>
    </Router>
  );
}

export default App;


这仅仅是因为您仅在“/”路由中呈现Auth组件

因此,如果您在不同的路线上,您将跳过“/”路线,并且将显示用户路线。有不同的处理方法:

  • 总是重定向
  • 提前返回

  • 另一个非常简单的解决方案可能就是这样做:

    <Route exact path="/" render={() => (logIn ? <SingleUser /> : <Auth />)} />
    
    (登录?:)}/>
    

    这样,在每次重新加载时,它都会检查是否有用户,如果没有,它会将您直接重定向到Auth组件。

    嗨,mike,过去的

    你的代码没问题,但是,当你点击注销时,App.js组件上的变量仍然是一样的,因此,你不会得到你想要的结果,你必须做的是重新加载网站,这样te App.js组件将上传变量,并识别变量的值已更改,因此,您将再次登录/注册

    只需更改这一个的代码,到目前为止一切都按预期工作

    import React from "react";
    
    import { useHistory } from "react-router-dom";
    import { useDispatch } from "react-redux";
    
    const SingleUser = () => {
      const history = useHistory();
      const dispatch = useDispatch();
    
      const logout = () => {
        dispatch({ type: "LOGOUT" });
    
        history.push("/");
        history.go("/");
      };
    
      return <div onClick={logout}>Single User</div>;
    };
    
    export default SingleUser;
    
    
    从“React”导入React;
    从“react router dom”导入{useHistory};
    从“react redux”导入{useDispatch};
    常量单用户=()=>{
    const history=useHistory();
    const dispatch=usedpatch();
    常量注销=()=>{
    分派({type:“LOGOUT”});
    历史。推送(“/”);
    历史。开始(“/”);
    };
    返回单个用户;
    };
    导出默认单用户;
    
    我明白了,但问题是,singleUser必须是一个类似于/profile/userId的路由,所以我将进行一些更改,但感谢您的回答!!谢谢你的朋友!我喜欢第三种解决方案,我会再试试,谢谢!
    <Switch>
            <Route exact path="/">
              <Auth />
            </Route>
            {!logIn && <Route path="*"><Redirect to={`/profile/${logIn.data.id}`} /></Route>} // This route will not always be rendered if the user should login and is not on the "/" page
            <Route exact path="/socialmedia" component={SocialMedia} />
            <Route exact path="/profile/:id" component={SingleUser} />
          </Switch>
    
    const SingleUser = () => {
      const history = useHistory();
      const dispatch = useDispatch();
    
      const userData = JSON.parse(localStorage.getItem("token"));
      if(!userData) histroy.push("/")
     ...
    
    function App() {
      const logIn = JSON.parse(localStorage.getItem("token"));
      if(!login) return <Auth />
      return (
        <Router>
          <Switch>
            <Route exact path="/">
              <Redirect to={`/profile/${logIn.data.id}`} />
            </Route>
            <Route exact path="/socialmedia" component={SocialMedia} />
            <Route exact path="/profile/:id" component={SingleUser} />
          </Switch>
        </Router>
      );
    }
    
    if (!userData) { // Remove the if
        history.push("/");
    }
    
    <Route exact path="/" render={() => (logIn ? <SingleUser /> : <Auth />)} />
    
    import React from "react";
    
    import { useHistory } from "react-router-dom";
    import { useDispatch } from "react-redux";
    
    const SingleUser = () => {
      const history = useHistory();
      const dispatch = useDispatch();
    
      const logout = () => {
        dispatch({ type: "LOGOUT" });
    
        history.push("/");
        history.go("/");
      };
    
      return <div onClick={logout}>Single User</div>;
    };
    
    export default SingleUser;