【发布时间】: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