Gapi не определяется при загрузке компонента React
Я пытаюсь интегрировать Google Sign In (ссылка) с помощью React.
Я нашел вопрос, который решил это в прошлом Использование кнопки входа в Google с ответом 2
Я воспроизвел те же шаги, что и упоминалось. В моем index.html
я делаю
<script src="https://apis.google.com/js/platform.js?onload=triggerGoogleLoaded" async defer></script>
<script type="text/javascript">
function triggerGoogleLoaded() {
console.log("google event loaded");
window.dispatchEvent(new Event('google-loaded'));
}
</script>
Затем мой Component
выглядит как
var LoginButton = React.createClass({
onSignIn: function(googleUser) {
console.log("user signed in"); // plus any other logic here
},
renderGoogleLoginButton: function() {
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
})
},
componentDidMount: function() {
window.addEventListener('google-loaded',this.renderGoogleLoginButton);
},
render: function() {
let displayText = "Sign in with Google";
return (
<div class="g-signin2" data-onsuccess="onSignIn"></div>
);
}
});
export default LoginButton;
Когда я запускаю программу с помощью yarn start
, я получаю
/Users/Harit.Himanshu/bl/sources/webs/google-login/src/LoginButton.js
11:9 error 'gapi' is not defined no-undef
26:13 warning 'displayText' is assigned a value but never used no-unused-vars
✖ 2 problems (1 error, 1 warning)
Полный исходный код доступен по адресу https://github.com/hhimanshu/google-login-with-react
Может кто-нибудь, пожалуйста, помогите мне понять мою ошибку?
Спасибо
Ответы
Ответ 1
Мне кажется, что вы загружаете google apis как тег script, который мы ожидаем установить window.gapi
в google api. Тем не менее, вы запускаете eslint или какую-то другую проверку, и это не имеет понятия, что window.gapi
должен существовать. Он не работает, потому что видит, что вы используете необъявленную переменную.
Дешевое решение - сказать Эслинту, что вы знаете, что вы делаете;
/* global gapi */
Поместите это вверху вашего файла, и eslint будет обрабатывать gapi
как известную глобальную переменную.
Ответ 2
Это сработало для меня. Поместите это в componentDidMount или конструктор:
componentDidMount() {
window.gapi.load('auth2', () => {
// Retrieve the singleton for the GoogleAuth library and set up the client.
this.auth2 = window.gapi.auth2.init({
client_id: '436676563344-.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
});
this.auth2.attachClickHandler(this.refs.googleButton, {},
(googleUser) => {
this.googleLogin(googleUser.getBasicProfile());
}, (error) => {
});
});
}
Ответ 3
Вы также можете попробовать пакет gapi-script, этот пакет мгновенно предоставляет gapi, поэтому вам не нужно ждать загрузки какого-либо скрипта, просто импортируйте его и используйте:
import { gapi } from 'gapi-script';