【发布时间】:2016-09-19 03:07:43
【问题描述】:
我的 SPA React/Firebase 应用程序的硬刷新不会在立即执行功能时保持身份验证状态。我有一个解决方法,但它很粗略。
我的反应路由使用onEnter 函数来确定用户是否经过身份验证。比如
<Route path="/secure" component={Dashboard} onEnter={requireAuth}/>
此外,我的requireAuth 函数如下所示:
function (nextState, replace) {
console.log('requireAuth', firebase.auth().currentUser);
if (!firebase.auth().currentUser) {
console.log('attempting to access a secure route. please login first.');
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
});
}
};
但是,在硬刷新时,firebase.auth().currentUser 会有一点延迟。一开始它是空的,然后对firebase服务器执行POST以确定身份验证状态。当它返回时,currentUser 对象被填充。但是,这种延迟会导致问题。
我的 hacky 解决方案如下:更新:这实际上不起作用...
function (nextState, replace) {
setTimeout(function () {
console.log('requireAuth', firebase.auth().currentUser);
if (!firebase.auth().currentUser) {
console.log('attempting to access a secure route. please login first.');
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
});
}
}, 50);
};
只需将其包装在超时中即可。但是,我真的不喜欢这样……有什么想法吗?
更新:
我还尝试将它封装在 onAuthStateChanged 侦听器中,这应该比带有明确时间延迟的 setTimeout 更准确。代码如下:
function (nextState, replace) {
var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
if (!user) {
console.log('attempting to access a secure route');
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
console.log('should have called replace');
}
unsubscribe();
});
// setTimeout(function () {
// console.log('requireAuth', firebase.auth().currentUser);
// if (!firebase.auth().currentUser) {
// console.log('attempting to access a secure route. please login first.');
// replace({
// pathname: '/login',
// state: { nextPathname: nextState.location.pathname }
// });
// }
// }, 50);
};
两条日志语句都执行了,但是react-routerreplace好像没有正确执行。对于 react-router 专家来说,这可能是一个不同的问题。
更新 2:
我做这个的时候已经很晚了。显然setTimeout 实际上也不起作用。
【问题讨论】:
-
我想我刚刚在这里回答了一个类似的问题:stackoverflow.com/questions/37370462/…
-
@FrankvanPuffelen 我实际上尝试过类似的方法。从 requireAuth 函数中将内容包装在 firebase.auth().onAuthStateChanged(function (user) {...});但是,在这种情况下,react-router 的替换功能似乎没有做任何事情。我会更新问题。
标签: reactjs firebase react-router firebase-authentication