【发布时间】:2019-08-17 09:04:00
【问题描述】:
我正在使用Firebase 为我的应用程序验证用户身份。我已经创建了SignIn 和SignUp 表单,并且可以成功创建新用户并使用存储的用户登录。但是,问题在于在 Reload 之后保持用户登录状态。
我在教程中看到的方法是使用HOC 如下所示来检查当前用户是否已登录。
const withAuthentication = Component => {
class WithAuthentication extends React.Component {
constructor(props) {
super(props);
this.state = {
authUser: null,
};
}
componentDidMount() {
this.listener = this.props.firebase.auth.onAuthStateChanged(
authUser => {
authUser
? this.setState({ authUser })
: this.setState({ authUser: null });
},
);
}
componentWillUnmount() {
this.listener();
}
render() {
return (
<AuthUserContext.Provider value={this.state.authUser}>
<Component {...this.props} />
</AuthUserContext.Provider>
);
}
}
return withFirebase(WithAuthentication);
};
export default withAuthentication;
但是我希望使用新的React Hooks 来消除对HOCs 的需求。我已经通过使用React Context 和useContext(FirebaseContext) 访问Firebase 的单个实例删除了withFirebase() HOC。有没有办法使用新的hooks 在我创建的components 中模仿withAuthentication HOC?
我正在使用这个教程
https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial/
标题为“高阶组件的会话处理”的部分包含此部分。
谢谢!
【问题讨论】:
-
一种选择是使用react-firebase-hooks 库,它通过其
useAuthState钩子支持onAuthStateChange -
谢谢 Jeff,我确实研究过这个,但是我想减少我的项目所具有的依赖项的数量,因为它将来维护最少,所以我不想太担心重大变化!
-
@TristanTrainer - 你明白了吗?我正在努力解决同样的问题stackoverflow.com/questions/59977856/…
标签: reactjs firebase firebase-authentication react-hooks