简体   繁体   English

React Router v5:history.push()改变地址栏,但不改变页面

[英]React Router v5: history.push() changes the address bar, but does not change the page

I am trying to redirect a user to a new page if a login is successful in my React app.如果在我的 React 应用程序中登录成功,我将尝试将用户重定向到新页面。 The redirect is called from the auth service which is not a component.重定向是从不是组件的身份验证服务调用的。 To access the history object outside of my component I followed this example in the React Router FAQ .为了在我的组件之外访问历史记录 object,我遵循了React Router 常见问题解答中的这个示例。 However, when I call history.push('/pageafterlogin') , the page is not changed and I remain on the login page (based on my Switch I would expect to end up on the 404 page).但是,当我调用history.push('/pageafterlogin')时,页面没有更改,我仍然停留在登录页面上(根据我的Switch ,我预计最终会出现在404页面上)。 The URL in the address bar does get changed to /pageafterlogin but the page is not changed from the login page.地址栏中的 URL 确实更改为/pageafterlogin但该页面未从登录页面更改。 No errors appear in the console or anything else to indicate my code does not work.控制台或其他任何地方都没有出现任何错误,表明我的代码不起作用。

How can I make history.push() also change the page the user is on?我怎样才能让history.push()也改变用户所在的页面?

// /src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();

// /src/App.js
...
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import history from './history';

function App() {
    return (
        <Router history={history}>
            <Switch>
                <Route path="/" exact component={HomePage} />
                <Route path="/login" exact render={() => <FormWrapper><LoginForm /></FormWrapper>} />
                <Route render={() => <h1>404: not found</h1>} />
            </Switch>
        </Router>
    );
}

export default App;

// src/services/auth.service.js
import axios from 'axios';
import history from '../history';

const API_URL = '...';

class AuthService {
    login(username, password) {
        return axios.post(API_URL + 'login', {
            username,
            password
        }).then(res => {
            if (res.status === 200) {
                localStorage.setItem('user', JSON.stringify(res.data));
                history.push('/pageafterlogin');
            }
        });
    }
}

Instead of using BrowserRouter , use Router from react-router-dom不要使用BrowserRouter ,而是使用react-router-dom Router

You could see the example here你可以在这里看到这个例子


import { Router, Route, Switch, useHistory, create } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import React from 'react';

const history = createBrowserHistory();


export default function App() {
    return (
        <Router history={history}>
            <Switch>
                <Route path="/" exact component={() => <h1>HomePage</h1>} />
                <Route path="/login" exact component={Login} />
                <Route render={() => <h1>404: not found</h1>} />
            </Switch>
        </Router>
    );
}


function Login() {
  React.useEffect(() => {
    history.push('/pageafterlogin')
  }, [])

  return <h1>Login page</h1>
}

If you are looking for a solution to this in 2022 and are using React V18+, the solution is that React v18 does not work well with react-router-dom v5.如果你正在寻找 2022 年的解决方案并且正在使用 React V18+,解决方案是 React v18 不能很好地与 react-router-dom v5 一起工作。

I have not tried with react-router-dom v6 yet, but downgrading to React V17 solved the issue for me.我还没有尝试使用 react-router-dom v6,但是降级到 React V17 为我解决了这个问题。

I removed StrictMode and it solved the problem我删除了StrictMode并解决了问题

import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import React from 'react';
const history = createBrowserHistory();


export default function MyApp() {
    return (
        <Router history={history}></Router>
    );
}

I had the same problem when I hadn't specified the vesion of 'history'.当我没有指定“历史”的版本时,我遇到了同样的问题。 You need to use a 4.x version with Router 5.x .您需要将4.x 版本与 Router 5.x一起使用。 For example, I use React v18, history v4.7.2 and react-router-dom v5.3.3 and it works fine.例如,我使用 React v18、history v4.7.2 和 react-router-dom v5.3.3,它运行良好。 Try尝试

npm i history@4.7.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM