如何从react-native-fbsdk获取用户信息(电子邮件,姓名等)?

时间:2016-05-26 22:13:25

标签: facebook react-native

当用户使用Facebook进行身份验证时,我尝试访问用户的电子邮件和名称以进行设置和帐户。我已经为react-native-fbsdk准备了文档,但我没有在任何地方看到它。

5 个答案:

答案 0 :(得分:41)

接受的答案使用fetch,但SDK也能够执行此请求...因此,如果有人想知道,这就是使用SDK的方法。

let req = new GraphRequest('/me', {
    httpMethod: 'GET',
    version: 'v2.5',
    parameters: {
        'fields': {
            'string' : 'email,name,friends'
        }
    }
}, (err, res) => {
    console.log(err, res);
});

有关详细信息,请参阅github.com/facebook/react-native-fbsdk#graph-requests

答案 1 :(得分:30)

你可以做这样的事情(这是我在我的应用程序中所做的简化版本):

<LoginButton
  publishPermissions={['publish_actions']}
  readPermissions={['public_profile']}
  onLoginFinished={
    (error, result) => {
      if (error) {
        console.log('login has error: ', result.error)
      } else if (result.isCancelled) {
        console.log('login is cancelled.')
      } else {
        AccessToken.getCurrentAccessToken().then((data) => {
          const { accessToken } = data
          initUser(accessToken)
        })
      }
    }
  }
  onLogoutFinished={logout} />

// initUser 功能

initUser(token) {
  fetch('https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=' + token)
  .then((response) => response.json())
  .then((json) => {
    // Some user object has been set up somewhere, build that user here
    user.name = json.name
    user.id = json.id
    user.user_friends = json.friends
    user.email = json.email
    user.username = json.name
    user.loading = false
    user.loggedIn = true
    user.avatar = setAvatar(json.id)      
  })
  .catch(() => {
    reject('ERROR GETTING DATA FROM FACEBOOK')
  })
}

答案 2 :(得分:8)

这对你有帮助,这对我有用

import React, { Component } from 'react';
import { View } from 'react-native';
import { LoginManager,LoginButton,AccessToken,GraphRequest,GraphRequestManager} from 'react-native-fbsdk';

export default class App extends Component<{}> {

  render() {
    return (
      <View style={styles.container}>

        <LoginButton
          publishPermissions={["publish_actions"]}
          onLoginFinished={
            (error, result) => {
              if (error) {
                alert("login has error: " + result.error);
              } else if (result.isCancelled) {
                alert("login is cancelled.");
              } else {
                AccessToken.getCurrentAccessToken().then(
                  (data) => {
                    const infoRequest = new GraphRequest(
                      '/me?fields=name,picture',
                      null,
                      this._responseInfoCallback
                    );
                    // Start the graph request.
                    new GraphRequestManager().addRequest(infoRequest).start();
                  }
                )
              }
            }
          }
          onLogoutFinished={() => alert("logout.")}/>
      </View>
    );
  }

  //Create response callback.
  _responseInfoCallback = (error, result) => {
    if (error) {
      alert('Error fetching data: ' + error.toString());
    } else {
      alert('Result Name: ' + result.name);
    }
  }
}

详情请访问此处,它将为您提供更多帮助。 Facebook Login React

答案 3 :(得分:3)

import React, { Component } from 'react';
import { View } from 'react-native';
import { LoginButton, AccessToken } from 'react-native-fbsdk';

export default class FBLogin extends Component {

    initUser = (token) => {
        fetch('https://graph.facebook.com/v2.5/me?fields=email,first_name,last_name,friends&access_token=' + token)
            .then((response) => {
                response.json().then((json) => {
                    const ID = json.id
                    console.log("ID " + ID);

                    const EM = json.email
                    console.log("Email " + EM);

                    const FN = json.first_name
                    console.log("First Name " + FN);
                })
            })
            .catch(() => {
                console.log('ERROR GETTING DATA FROM FACEBOOK')
            })
    }

    render() {
        return (
            <View>
                <LoginButton
                    publishPermissions={['publish_actions']}
                    readPermissions={['public_profile']}
                    onLoginFinished={
                        (error, result) => {
                            if (error) {
                                console.log('login has error: ', result.error)
                            } else if (result.isCancelled) {
                                console.log('login is cancelled.')
                            } else {
                                AccessToken.getCurrentAccessToken().then((data) => {
                                    const { accessToken } = data
                                    // console.log(accessToken);
                                    this.initUser(accessToken)
                                })
                            }
                        }
                    }
                    onLogoutFinished={() => {
                        console.log('Logout');
                    }}
                />
            </View>
        );
    }
};

答案 4 :(得分:3)

这是获取 Facebook 个人资料信息的完整代码片段。

“反应”:“16.13.1”
“反应原生”:“0.63.3”
"react-native-fbsdk": "^3.0.0"

const infoRequest = new GraphRequest(
    '/me', 
    {
      parameters: {
        'fields': {
            'string' : 'email,name'
        }
      }
    },
    (err, res) => {
      console.log(err, res);
    }
);

const facebookLogin = () => {
    LoginManager.logInWithPermissions(["public_profile", "email"]).then(
      function(result) {
        if (result.isCancelled) {
          console.log("Login cancelled");
        }
        else {
          console.log("Login success with permissions: " + result.grantedPermissions.toString());
          new GraphRequestManager().addRequest(infoRequest).start();
        }
      },
      function(error) {
        console.log("Login fail with error: " + error);
      }
    );
}