(React-Native) Возможное отклонение необработанного обещания FBSDK

Итак, у меня есть этот код:

export default class Login extends Component {

  constructor(props){
    super(props);
    this._fbAuth = this._fbAuth.bind(this);
    this.login = this.login.bind(this);
  }

  login(){
      this.props.navigator.push({
        id: "Home",
      });
  }

  _fbAuth(){
    LoginManager.logInWithReadPermissions(['public_profile']).then(
      function(result) {
        if (result.isCancelled) {
          alert('Login cancelled');
        } else {
alert('Login success with permissions: '+result.grantedPermissions.toString());
          this.login();
        }
      },
      function(error) {
        alert('Login fail with error: ' + error);
      }
    );
  }

  render() {
    return (
      <View style={styles.container}>
              <View style={styles.botbuttoncontainer}>
                <Text style={styles.otherlogintext}>Or log in using</Text>
                <View style={styles.otherloginbutton}>
                <TouchableOpacity style={styles.facebookbutton} activeOpacity={0.5} onPress={()=>this._fbAuth()}>
                  <Icons name="logo-facebook" size={20} color="white"/>
                </TouchableOpacity>
                <TouchableOpacity style={styles.twitterbutton} activeOpacity={0.5}>
                  <Icons name="logo-twitter" size={20} color="white"/>
                </TouchableOpacity>
                <TouchableOpacity style={styles.googlebutton} activeOpacity={0.5}>
                  <Icons name="logo-googleplus" size={20} color="white"/>
                </TouchableOpacity>
                </View>
              </View>
      </View>
    );
  }
}

Каждый раз, когда я пытаюсь войти в систему через facebook, это успешно. но я всегда получаю предупреждение говорит

«Возможное отклонение необработанного обещания (id: 0): TypeError: undefined не является функцией (оценка 'this.login ()')»

Я пытаюсь связать как функцию _fbAuth, так и вход в конструктор, но он все равно дает такое же предупреждение.


person arnold tan    schedule 31.10.2017    source источник


Ответы (1)


Вам нужно привязать внутреннюю функцию вызова.

Пример

LoginManager.logInWithReadPermissions(['public_profile']).then(
  function (result) {
    if (result.isCancelled) {
      alert('Login cancelled');
    }
    else {
      alert('Login success with permissions: ' + result.grantedPermissions.toString());
      this.login();
    }
  }.bind(this),
  function (error) {
    alert('Login fail with error: ' + error);
  }
);

Или вы можете использовать стрелочные функции

LoginManager.logInWithReadPermissions(['public_profile']).then(
  (result) => {
    if (result.isCancelled) {
      alert('Login cancelled');
    }
    else {
      alert('Login success with permissions: ' + result.grantedPermissions.toString());
      this.login();
    }
  },
  function (error) {
    alert('Login fail with error: ' + error);
  }
);

Еще одна хорошая практика - использовать catch при использовании Promise.

Пример

LoginManager.logInWithReadPermissions(['public_profile']).then(
  (result) => {
    if (result.isCancelled) {
      alert('Login cancelled');
    }
    else {
      alert('Login success with permissions: ' + result.grantedPermissions.toString());
      this.login();
    }
  },
  function (error) {
    alert('Login fail with error: ' + error);
  }
).catch((error) => console.error(error)); // error handling for promise
person bennygenel    schedule 31.10.2017
comment
Это работает! Большое спасибо, сэр. Сначала я, хотя привязки на _fbAuth, достаточно. - person arnold tan; 31.10.2017