【问题标题】:history.replace() not working in auth0 class and react-router v4history.replace() 在 auth0 类和 react-router v4 中不起作用
【发布时间】:2019-09-11 01:15:21
【问题描述】:

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() 包装组件,但这似乎仅适用于组件,而这种情况下我试图只使用一个类。

【问题讨论】:

    标签: javascript reactjs react-router auth0 history.js


    【解决方案1】:

    您在运行控制台时是否看到任何错误?这似乎与 Auth0 没有直接关系,更多的是在被调用时填充到顶部的道具方面。谢谢!

    【讨论】:

    • 你是对的,它与 Auth0 没有直接关系,但更多的是与从非组件类访问历史记录有关
    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2017-12-15
    • 2017-09-04
    • 2017-11-02
    • 2018-09-06
    • 2017-08-02
    • 2018-02-10
    相关资源
    最近更新 更多