【发布时间】:2017-12-07 21:25:01
【问题描述】:
我有一个连接到 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 的定义时间,但我不喜欢那个解决方案。想法?谢谢
【问题讨论】:
-
您可以使用 componentWillMount 代替 componentDidMount 并使用条件渲染:)
标签: reactjs firebase authentication redux redux-thunk