我一整天都在努力讓Google身份驗證與React一起工作,但是在搜索了幾個小時後,我發現我只找到了一輛越野車,有時候會工作,一團糟。任何人都可以看到我做錯了什麼? (這是一個學校項目,所以我正在學習!)如何讓Google身份驗證與ReactJs配合使用?
該項目將成爲一個在線時間表創作者。
我主要Index.js具有以下渲染功能:
function renderApp() {
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={Login}></Route>
<Route component={AuthUserContainer}>
<Route path="/auth" component={Layout}>
<IndexRoute component={Overview}></IndexRoute>
<Route path="schedule(/:scheduleid)" component={Schedule}></Route>
</Route>
</Route>
</Router>,
app);
}
家庭頁是一個簡單的登錄頁面,通過登錄組件處理,將用戶重定向到/ AUTH如果認證成功的。 AuthUserContainer會在每次訪問受保護的路由時持續處理認證。
登錄組件具有Google登錄按鈕,所有受保護的路由都具有(通過佈局組件)Google登出按鈕。
我Header.js包含「谷歌退出按鈕」(signOutHandler):
export default class Header extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.SignOutHandler = this.SignOutHandler.bind(this);
}
SignOutHandler() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function() {
console.log('User signed out.');
Authenticate.signOutUser();
});
}
render() {
return (
<div class="header-content">
<h2 class="header-title">Schedule</h2>
<h3 class="header-user-button">
<a href="/" onClick={this.SignOutHandler}>User First Name</a>
</h3>
</div>
);
}
}
我使用谷歌自己的示例代碼,並試圖調整它的反應。我用這段代碼得到的問題是「Uncaught TypeError:無法讀取未定義的屬性'getAuthInstance'」。由於我將登錄和退出按鈕分割成單獨的頁面,因此auth2不能正確初始化,但單擊按鈕兩次可使其正常工作。試圖手動經常在這裏初始化它給我的錯誤是加皮是不確定...
最後Login.js:
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.onSignIn = this.onSignIn.bind(this);
this.renderGoogleLoginButton = this.renderGoogleLoginButton.bind(this);
}
renderGoogleLoginButton() {
console.log('rendering google signin button')
gapi.signin2.render('my-signin2', {
'scope': 'https://www.googleapis.com/auth/plus.login',
'width': 200,
'height': 50,
'longtitle': true,
'theme': 'light',
'onsuccess': this.onSignIn
});
gapi.load('auth2', function() {
gapi.auth2.init();
});
}
componentDidMount() {
window.addEventListener('google-loaded', this.renderGoogleLoginButton);
}
onSignIn(googleUser) {
Authenticate.signInUser(googleUser.getBasicProfile());
this.props.router.push("/auth");
}
render() {
return (
<div class="container">
<h2 class="form-signin-heading">
Sign-in with Google account required
</h2>
<div id="my-signin2"></div>
</div>
);
}
}
我也是基於這個代碼在谷歌自己的,但沒有奏效根本沒有(按鈕沒有加載,根本沒有顯示,或者它從來沒有調用過onSignIn)。我也發現並嘗試this,這使得它有點工作(有時)。我也嘗試在renderGoogleLoginButton()中初始化auth2,但這隻能在有時和...
renderGoogleLoginButton()由自定義事件(谷歌加載)的偶處理程序調用,它會在Google API加載時觸發(完全像在鏈接中)。 Authenticate是我自己的類,它捆綁在一起我創建的令牌,getUserName函數等。
我還從gapi中得到以下錯誤:「Uncaught TypeError:無法讀取屬性'style'的null」,我認爲它試圖引用登錄/註銷按鈕,但由於它們在空時沒有加載。
我找不到任何不會導致故障或錯誤的良好解決方案。 Googles own code將所有內容放在同一個HTML文檔中,但由於我想將它分解爲組件,所以它全部中斷。我可能完全錯了嗎?我對React很新,但希望這是可以理解的!
對不起,很長時間的文章,非常感謝你的時間,如果你有任何問題只是問!