如何从React Native中的Firebase身份验证调度Redux操作

时间:2017-06-27 15:36:27

标签: javascript firebase react-native firebase-authentication react-redux

我正在尝试使用firebase auth listener根据文档调度logIn函数。但是我想使用监听器触发一个redux动作来填充我的状态。

当我尝试运行以下代码时,在使用firebase成功登录后,它将失败并显示“无法读取未定义的属性'logIn'。

请停止

class RootApp extends Component {
    componentWillMount() {
        // Listen for Auth Changes
        firebase.auth().onAuthStateChanged(function(user) {
            if (user) {
                this.props.logIn(
                    uid,
                    displayName,
                    photoURL,
                    providerId,
                    email,
                    emailVerified
                );
                // User is signed in.
            } else {
                console.log("Not logged in");
                // No user is signed in.
            }
        });
    }

    render() {
        if (this.props.auth.checking == true) {
            return (
                <ActivityIndicator
                    animating={true}
                    style={styles.activityIndicator}
                    size="large"
                />
            );
        } else if (this.props.auth.signedIn == true) {
            return <SignedIn />;
        } else {
            return <SignedOut />;
        }
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "#fff",
        alignItems: "center",
        justifyContent: "center",
        fontSize: 96
    },
    activityIndicator: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        height: 80
    }
});

const mapStateToProps = state => {
    return {
        auth: state.auth
    };
};

const mapDispatchToProps = dispatch => {
    return {
        logIn: (
            uid,
            displayName,
            photoURL,
            providerId,
            email,
            emailVerified
        ) => {
            dispatch(
                logIn(
                    uid,
                    displayName,
                    photoURL,
                    providerId,
                    email,
                    emailVerified
                )
            );
        }
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(RootApp);

1 个答案:

答案 0 :(得分:0)

对于其他人来说,答案是将firebase示例侦听器函数转换为胖箭头函数,因为在他们的示例中使用的旧式函数绑定了它自己的&#39;这个&#39;,哪个箭头功能不起作用。

所以这个:

firebase.auth()。onAuthStateChanged(function(user){

需要改为:

firebase.auth()。onAuthStateChanged(user =&gt; {