簡體   English   中英

React-native this.props 在回調 function 中為空

[英]React-native this.props is empty in callback function

我正在嘗試在我的 class 中實現 Facebook 登錄。 我創建了一個按鈕組件,但是當我調用 Facebook api 並嘗試分派一個寄存器 function 時,我得到了未定義的道具。 這是我的組件:

import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { LoginManager, AccessToken, GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
import Icon from 'react-native-vector-icons/FontAwesome';
import { connect } from 'react-redux';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {register} from '../Actions/authActions';

class Login extends Component {
    constructor(props) {
        super(props);
    }

    _fbAuth = () => {
        LoginManager.logInWithPermissions(['public_profile','email']).then(function(result){
            if(result.isCancelled){
                console.log('loging cancelled')
            }
            else {
                AccessToken.getCurrentAccessToken().then((data) => {
                    let accessToken = data.accessToken;
                    let facebookId = data.userID;
                    const responseInfoCallback = (error, result) => {
                        if (error) {
                            alert('Error logging in with Facebook');
                        }
                        else {
                            console.log('Props here are empty', this.props);
                            this.props.registerSubmit({
                                "customerName": result.name,
                                "customerTel": '000000000',
                                "customerEmail": result.email,
                                "customerPassword": facebookId
                            }).then(response => {
                                console.log('RESPONSE', response);
                                if (response && response.Success) {
                                    this.props.navigation.navigate('App');
                                    AsyncStorage.setItem('customerEmail', data.email);
                                    AsyncStorage.setItem('customerPassword', data.password);
                                } else {
                                    this.props.navigation.navigate('Auth');
                                }
                            });
                        }
                    }
                    const infoRequest = new GraphRequest('/me', {
                        accessToken: accessToken, 
                        parameters: {
                            fields: {
                                string: 'name,picture,email'
                            }}
                        }, responseInfoCallback);
                    new GraphRequestManager().addRequest(infoRequest).start();
                });
            }}, function (error) {
                console.log('Error logging with facebook');
            });
     }


    render() {
    return (
        <View style={styles.container}>
        <Icon.Button name="facebook" backgroundColor="#3b5998" onPress={this._fbAuth.bind(this)} style={styles.signInButton}>
          Facebook login
        </Icon.Button>
    </View>
    )
}
};

const mapDispatchToProps = (dispatch) => {
    // Action
    return {
        // Login
        registerSubmit: (data) => dispatch(register(data)),
    };
};

const styles = StyleSheet.create({
container: {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
},
signInButton: {
  width: 358,
  height: 48
}
});

export default connect(null, mapDispatchToProps)(Login);

當我進入回調 function this.props 是空的,因此 registerSubmit 是未定義的。 這是我第一個使用 class 組件的項目,我通常使用掛鈎。 我究竟做錯了什么?

當您運行此行時:

LoginManager.logInWithPermissions(['public_profile','email']).then(function(result){

新的function (result) { scope有自己的this

為了訪問組件的this ,您可以在回調外部保存對它的引用,然后在回調內部使用它:

const componentProps = this.props
LoginManager.logInWithPermissions(['public_profile','email']).then(function(result){

或者,您可以為您的回調使用“箭頭函數”,它沒有自己的this ,如下所示:

LoginManager.logInWithPermissions(['public_profile','email']).then(result => {

(注意我們不再使用function關鍵字了)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM