如何使用Facebook Login和ReactJS实现登录和注销? [英] How to implement login and logout with Facebook Login and ReactJS?

查看:206
本文介绍了如何使用Facebook Login和ReactJS实现登录和注销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Facebook登录名让用户使用React和React-Router登录和退出我的Web应用程序.我制作了一个组件,该组件可在成功登录后重定向用户,但无法在新视图上呈现注销按钮.我也是React-Router的新手,所以我不能完全确定问题是否出在我的路由上.

I'm trying to use Facebook Login for users to log in and out of my web app using React and React-Router. I made a component which redirects a user on successful login, but I am not able to render the log out button on the new view. I am also new to React-Router so I'm not entirely sure if the problem is with my routes.

到目前为止,这是我的代码:

Here's my code so far:

login.js

class Login extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            loggedStatus: false,
            id : ''
        }
    }

    componentDidMount() {
        window.fbAsyncInit = function() {
            window.FB.init({
                appId      : '',
                cookie     : true,  
                xfbml      : true,
                version    : 'v2.11'
            });

            window.FB.getLoginStatus(function(response) {
                this.statusChangeCallback(response);
            }.bind(this));
        }.bind(this);

        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.11&appId=''";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'))
    }

    loggedIn(response) {
        this.setState({
            loggedStatus : true,
            id: response.authResponse.userID        
        });         
    }

    loggedOut() {
        this.setState({
            loggedStatus: false,
        })
    }

    statusChangeCallback(response) {
      console.log('statusChangeCallback');
      console.log(response);
      if (response.status === 'connected') {
        this.loggedIn(response)
        console.log(this.state);
      } else if (response.status === 'not_authorized') {
        this.loggedOut()
        console.log(this.state.loggedStatus);
      } else {
        this.loggedOut()
         console.log(this.state.loggedStatus);
      }
    }

    checkLoginState() {
      window.FB.getLoginStatus(function(response) {
        this.statusChangeCallback(response);
      }.bind(this));
    }

    handleClick() {
      window.FB.login(this.checkLoginState());
    }

    render () {
        if (!this.state.loggedStatus) {
        return (
            <div className="fb-login-button" 
                 data-max-rows="1" 
                 data-size="large" 
                 data-button-type="continue_with" 
                 data-show-faces="false" 
                 data-auto-logout-link="true" 
                 data-use-continue-as="true">
            </div>   );
        } else {
            return (
                <Redirect to = {{
                    pathname : '/loggedin',
                    state : {
                        id: this.state.id
                    }
                }} />
            )
        }
    }

}

export default Login;

loggedin.js

loggedin.js

class UserLogin extends React.Component {
    constructor(props) {
        super(props);
        this.state =  {
            id: this.props.location.state.id
        }
    }
   render(){
      return (
    <div>Hey {this.state.id}!</div>
    </div>)

    }
}

export default UserLogin

这是我的主要应用App.js

And here is my main app, App.js

class App extends React.Component {
   render() {
      return (
        <Router>
            <Switch path = '/'>
                <Route path = '/login' component = {Login} />
                <Route path = '/loggedin' component = {UserLogin} />
            </Switch>
        </Router>
     );
   }
};

export default App;

推荐答案

然后我想您在设置路由器时遇到了问题.

Then I guess you have problem with router setup.

//Solution suppose you are using creat-react-app
//At index.js of you app put this.
//other import.

//install history package from npm

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();


ReactDOM.render(
       <Router history ={history}>
            <App/>
        </Router>,   
 document.getElementById('root'));
registerServiceWorker();

//at app.js file
//other required import
import { BrowserRouter, Route } from "react-router-dom";

//import your two component here



class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          <Route exact path="/login" component={Login} />
          <Route exact path="/loggedin" component={Loggedin} />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

// Inside Login component
// Use componentDidMount life cycle hook to redirect.


componentDidMount(){
  //other logic and at last...
  if(this.state.id !== null){
  const {history} = this.props;
  history.push('/loggedin') //redirection link if user is already logged in.
  }
  
}  

这篇关于如何使用Facebook Login和ReactJS实现登录和注销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆