【问题标题】:Authentication custom redirect callback身份验证自定义重定向回调
【发布时间】:2018-08-24 13:37:38
【问题描述】:

我已使用 Javascript SDK 将 Firebase/身份验证与我的 React Web 应用程序集成。我使用重定向方法设置 Github 登录。在用户成功通过 Github 进行身份验证后,他们将被重定向回我的登录表单。我已将侦听器 onAuthStateChanged 设置为我的 componentWillMount,以便在识别到用户后推送路由。

我想在onAuthStateChanged 检查用户状态时显示一个加载图标。但是,我无法知道该页面是从 Firebase 重定向调用的,除非回调在 url 中包含某些内容,即。 website.com/login-form/from-firebase-callback/

关于如何设置的任何想法?我浏览了文档,但找不到任何东西。我希望这是某个地方的快速配置修复,因为我不想手动设置流程。

class LoginForm extends React.Component {
    componentWillMount() {

        // would like to add a something to the url from the firebase redirect
        const query = queryString.parse(this.props.location.search);
        if (query === 'from-firebase-callback') {
            this.isLoading = true;
        }

        const authChangedListener = auth.onAuthStateChanged((user) => {
            if (user) {
                this.loading = false;
                this.props.history.push('/dashboard/');
            } else {
                console.log('no user...');
            }
        });
    }

... rest of component

【问题讨论】:

    标签: reactjs firebase authentication provider


    【解决方案1】:

    您可以结合使用 onAuthStateChanged 侦听器通过检查 state.user 和 state.loading 来确定用户是否登录,而不是陷入无法从不同 URL 传递状态的困境加载状态。

    class LoginForm extends React.Component {
        constructor(){
             super();
    
             this.state={
                 loading:true
             }
        }
    
        componentWillMount() {
            firebase.auth().onAuthStateChanged((user) => {
                if (user) {
                    this.setState({loading:false,user})
                    this.props.history.push('/dashboard/');
                } else {
                    this.setState({loading:false})
                }
            });
        }
        ... rest of component
    }
    

    【讨论】:

    • 感谢这个工作,我想多了,并没有完全理解 onAuthStateChanged 是如何工作的,但是 else 子句确实返回了正确的状态
    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 2023-03-25
    • 2013-12-10
    • 1970-01-01
    • 2020-04-01
    • 2022-12-10
    • 2020-01-14
    • 2016-04-11
    相关资源
    最近更新 更多