簡體   English   中英

React Router v5:history.push()改變地址欄,但不改變頁面

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

如果在我的 React 應用程序中登錄成功,我將嘗試將用戶重定向到新頁面。 重定向是從不是組件的身份驗證服務調用的。 為了在我的組件之外訪問歷史記錄 object,我遵循了React Router 常見問題解答中的這個示例。 但是,當我調用history.push('/pageafterlogin')時,頁面沒有更改,我仍然停留在登錄頁面上(根據我的Switch ,我預計最終會出現在404頁面上)。 地址欄中的 URL 確實更改為/pageafterlogin但該頁面未從登錄頁面更改。 控制台或其他任何地方都沒有出現任何錯誤,表明我的代碼不起作用。

我怎樣才能讓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');
            }
        });
    }
}

不要使用BrowserRouter ,而是使用react-router-dom Router

你可以在這里看到這個例子


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>
}

如果你正在尋找 2022 年的解決方案並且正在使用 React V18+,解決方案是 React v18 不能很好地與 react-router-dom v5 一起工作。

我還沒有嘗試使用 react-router-dom v6,但是降級到 React V17 為我解決了這個問題。

我刪除了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>
    );
}

當我沒有指定“歷史”的版本時,我遇到了同樣的問題。 您需要將4.x 版本與 Router 5.x一起使用。 例如,我使用 React v18、history v4.7.2 和 react-router-dom v5.3.3,它運行良好。 嘗試

npm i history@4.7.2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM