登录功能后history.push不起作用

我尝试history.push()在设置令牌后使用。不知何故,页面没有重定向到新路径。我已经使用了useHistory访问历史记录的功能。一旦我重新加载页面,它就会重定向到主页。我尝试了其他类型的黑客但无法找到解决方案。请帮忙。


应用程序.js


function App() {

  const [isAuthenticated, setAuthenticated] = useState(false);

  useEffect(()=>{

    if(cookie.get('authorization')){

      setAuthenticated(true);

    }

    else{

      setAuthenticated(false);

    }

  },[])

  return (

    <Router>

      <Switch>

        <Route exact path="/">

          {isAuthenticated?<Redirect to="/home"/>:<Login />}

        </Route>

        <PrivateRoute exact path="/user/:id" component={UserDetail} auth={isAuthenticated} />

        <PrivateRoute exact path="/createuser" component={CreateUser} auth={isAuthenticated} />

        <PrivateRoute exact path="/home" component={ListUser} auth={isAuthenticated} />

      </Switch>

    </Router>

  );

}


export default App;

登录.js


import React, { useEffect, useState } from 'react';

import {useHistory} from 'react-router-dom';


function Login() {

    const history = useHistory();

    const loginUser = (body) => {

        SetLoader(true);

        fetch('/api/v2/users/tokens', {

            method: 'POST',

            body: JSON.stringify(body),

            headers: {

                'Content-Type': 'application/json',

            }

        })

            .then(response => {

                SetLoader(false);

                if (response.status == 200) {

                    SetError(false);   

                    cookie.set('authorization',response.headers.map.authorization,{path:'/'});

                    history.push('/');

                }

                else {

                    SetError(true);

                    StoreResponse(JSON.parse(response._bodyInit).message);

                }

            })

            .catch((error) => {

                console.error('Error:', error);

            });

    }

}


export default Login;


青春有我
浏览 135回答 1
1回答

慕田峪7331174

我没有看到组件history中定义的位置Login。此外,您还设置了 cookie,但isAuthenticated仅在App组件安装时设置,以后绝不会更新。您可以传递回调来Login更新状态,并在重新渲染和重新渲染具有重新封闭状态的路由App时让重定向自然发生。它还已经尝试专门匹配和渲染路线,因此将您的路径从最具体到最不具体排序,并且您不需要将 prop 添加到每个路线。AppisAuthenticatedSwitchexact应用程序function App() {&nbsp; const [isAuthenticated, setAuthenticated] = useState(false);&nbsp; useEffect(() => {&nbsp; &nbsp; if (cookie.get("authorization")) {&nbsp; &nbsp; &nbsp; setAuthenticated(true);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; setAuthenticated(false);&nbsp; &nbsp; }&nbsp; }, []);&nbsp; return (&nbsp; &nbsp; <Router>&nbsp; &nbsp; &nbsp; <Switch>&nbsp; &nbsp; &nbsp; &nbsp; <PrivateRoute&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/user/:id"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; component={UserDetail}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; auth={isAuthenticated}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; <PrivateRoute&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/createuser"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; component={CreateUser}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; auth={isAuthenticated}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; <PrivateRoute&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path="/home"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; component={ListUser}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; auth={isAuthenticated}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; <Route path="/">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {isAuthenticated ? (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Redirect to="/home" />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ) : (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Login setAuthenticated={setAuthenticated} /> // <-- pass callback&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )}&nbsp; &nbsp; &nbsp; &nbsp; </Route>&nbsp; &nbsp; &nbsp; </Switch>&nbsp; &nbsp; </Router>&nbsp; );}登录function Login({ setAuthenticated }) { // <-- destructure prop&nbsp; const loginUser = (body) => {&nbsp; &nbsp; SetLoader(true);&nbsp; &nbsp; fetch("/api/v2/users/tokens", {&nbsp; &nbsp; &nbsp; method: "POST",&nbsp; &nbsp; &nbsp; body: JSON.stringify(body),&nbsp; &nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; &nbsp; "Content-Type": "application/json"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .then((response) => {&nbsp; &nbsp; &nbsp; &nbsp; if (response.status == 200) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SetError(false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cookie.set("authorization", response.headers.map.authorization, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; path: "/"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setAuthenticated(true); // <-- set authenticated&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SetError(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; StoreResponse(JSON.parse(response._bodyInit).message);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch((error) => {&nbsp; &nbsp; &nbsp; &nbsp; console.error("Error:", error);&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .finally(() => {&nbsp; &nbsp; &nbsp; &nbsp; SetLoader(false); // <-- set loading false in finally block&nbsp; &nbsp; &nbsp; });&nbsp; };&nbsp; ...}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript