【问题标题】:How to dispatch Redux action from Firebase auth in React Native如何在 React Native 中从 Firebase 身份验证调度 Redux 操作
【发布时间】:2017-11-30 18:02:09
【问题描述】:

根据文档,我正在尝试使用 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);

【问题讨论】:

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


    【解决方案1】:

    对于其他遇到此问题的人,答案是将 firebase 示例侦听器函数转换为粗箭头函数,因为在他们的示例中使用的老式函数绑定了它自己的“this”,而箭头函数不这样做。

    所以这个:

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

    需要改成:

    firebase.auth().onAuthStateChanged(user => {

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-10
      • 2018-03-10
      • 2017-07-12
      • 2016-12-25
      • 1970-01-01
      • 2017-06-13
      • 2015-08-28
      • 1970-01-01
      相关资源
      最近更新 更多