我有一个连接到 Firebase 的 React 应用程序,我想检查用户是否在每次页面刷新、调度IS_SIGNED_IN操作时登录,这是操作创建者:
export function checkAuth() {
return dispatch => {
firebaseAuth().onAuthStateChanged((user) => {
if (user) {
dispatch(signedInAction())
} else {
dispatch(signedOutAction())
}
})
}
}
在减速器中,我只是将布尔值isAuthenticated设为真/假:
case ActionTypes.isSignedIn: {
return Object.assign({}, state, {
isAuthenticated: true
})
}
case ActionTypes.isSignedOut: {
return Object.assign({}, state, {
isAuthenticated: false
})
}
因为我想检查用户是否在应用加载时登录,所以我将操作发送到componentDidMount(我猜这是错误的):
class Main extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
store.dispatch(checkAuth());
}
render() {
return (
<Provider store={store}>
<Router>
<Theme>
<Routes />
</Theme>
</Router>
</Provider>
);
}
}
这使我检查的代码isAuthenticated失败,因为它尚未在商店中设置,Routes例如在组件中。解决这个问题的最佳方法是什么?总而言之,我知道我可以使用条件渲染并检查何时isAuthenticated定义,但我不喜欢该解决方案。想法?谢谢