最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Router v5: history.push() changes the address bar, but does not change the page - Stack Overflow

programmeradmin3浏览0评论

I am trying to redirect a user to a new page if a login is successful in my React app. 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. 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). The URL in the address bar does get changed to /pageafterlogin but the page is not changed from the login page. 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?

// /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');
            }
        });
    }
}

I am trying to redirect a user to a new page if a login is successful in my React app. 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. 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). The URL in the address bar does get changed to /pageafterlogin but the page is not changed from the login page. 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?

// /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');
            }
        });
    }
}
Share Improve this question edited Nov 11, 2021 at 10:22 ouflak 2,50410 gold badges45 silver badges52 bronze badges asked Aug 24, 2020 at 3:10 No stupid questionsNo stupid questions 4851 gold badge14 silver badges40 bronze badges 5
  • have you defined the path of the route in Route component? – Prateek Thapa Commented Aug 24, 2020 at 3:11
  • Sorry could you clarify what you mean? history is passed to the Router component and the Routes are inside a Switch so even if /pageafterlogin isn't defined it should default to the 404 page. – No stupid questions Commented Aug 24, 2020 at 3:14
  • If you're using history you can not use BrowserRouter you need to import Router... If you open the console you'll see - Warning: <BrowserRouter> ignores the history prop. To use a custom history, use import { Router } instead of import { BrowserRouter as Router }. – SakoBu Commented Aug 24, 2020 at 4:03
  • @SakoBu Besides that, are there any differences between BrowserRouter and Router that would have an impact elsewhere in my code? – No stupid questions Commented Aug 24, 2020 at 4:04
  • Yes - they take different props: BrowserRouter - reactrouter.com/web/api/BrowserRouter Router - reactrouter.com/web/api/Router (you can see it takes the history prop) There are also HashRouter, MemoryRouter etc... – SakoBu Commented Aug 24, 2020 at 4:08
Add a comment  | 

5 Answers 5

Reset to default 5

Instead of using BrowserRouter, use Router from react-router-dom

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.

I have not tried with react-router-dom v6 yet, but downgrading to React V17 solved the issue for me.

I removed StrictMode and it solved the problem

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. For example, I use React v18, history v4.7.2 and react-router-dom v5.3.3 and it works fine. Try

npm i [email protected]
发布评论

评论列表(0)

  1. 暂无评论