簡體   English   中英

history.replace()在auth0類和react-router v4中不起作用

[英]history.replace() not working in auth0 class and react-router v4

history.replace()在auth0類中不起作用

//src/history.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

然后,我嘗試將其導入到我的Auth0類中以使用history.replace()。 這是該類中的兩個函數,以及我如何嘗試使用此函數。

//components/Auth.js

handleAuthentication() {
        this.auth0.parseHash((err, authResult) => {
            if (authResult && authResult.accessToken && authResult.idToken) {
                this.setSession(authResult);
            } else if (err) {
                console.log(err);
                alert(`Error: ${err.error}. Check the console for further details.`);

                location.hash = "";
                //location.pathname = "/";
                history.replace("/");
            }
        });
    }

    setSession(authResult) {
        // Set isLoggedIn flag in localStorage
        //localStorage.setItem('isLoggedIn', 'true');

        // Set the time that the access token will expire at
        let expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());

        localStorage.setItem("access_token", authResult.accessToken);
        localStorage.setItem("id_token", authResult.idToken);
        localStorage.setItem("expires_at", expiresAt);

        location.hash = "";
        //location.pathname = "/dashboard";
        history.replace("/dashboard");

    }

我還將歷史記錄作為道具添加到路由器中。

<Router history={history}>
            <Switch>
                <Route exact path="/" render={(props) => <Home auth={this.props.auth} {...props} />}/>
                <Route path="/dashboard" render={(props) => <Dashboard auth={this.props.auth} {...props} />}/>
                <Route path="/callback" render={(props) => <Callback auth={this.props.auth} {...props} />}/>
            </Switch>
</Router>

我讀過用withRouter()包裝一個組件,但這似乎僅對組件有效,在這種情況下,我試圖只使用一個類。

運行控制台時是否看到任何錯誤? 這似乎與Auth0沒有直接關系,在調用該屬性時,該屬性在頂部居高不下。 謝謝!

暫無
暫無

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

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