首页 > 解决方案 > 无法在反应本机功能中读取“this”

问题描述

我正在尝试从 facebook 登录设置用户数据并将其存储在一个状态但发生错误。

脸书认证

_fbAuth(){
  LoginManager.logInWithReadPermissions(['public_profile']).then(function(res){
    if(res.isCancelled){
      console.log('login cancelled.')
    } else {
      AccessToken.getCurrentAccessToken().then(tokenData => {
        if(tokenData) {
          const { accessToken, userID } = tokenData;
          fetch('https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=' + accessToken).then((response) => 
            response.json()).then((json) => {
              this.setState({ user_email: json.email })
            }).catch(() => {
              reject('ERROR GETTING DATA FROM FACEBOOK')
            }
          )
        }
      })
    }
  }, function(err){
    console.log(err)
  })
}

将数据注册到引发此错误的状态:

[TypeError: undefined is not a function (evalating '_this3.setState({ user_email: json.email })')]

我应该如何访问响应this内部?fetch()

标签: react-nativethisfacebook-loginfbsdk

解决方案


在您的构造函数中添加此行以将组件上下文绑定到函数范围。

this._fbAuth = this._fbAuth.bind(this);

这应该工作!


推荐阅读