【发布时间】:2020-09-26 18:31:29
【问题描述】:
我正在尝试将基于类的组件重构为使用钩子的函数式组件。在尝试获取我的登录状态时,我陷入了在 gapi 中正确使用 useState 的问题。
只是想知道,我想得到什么:
1) 初始化后获取“auth”对象的引用
2) 弄清楚我当前是否已登录
3) 在屏幕上打印我的身份验证状态
这里已经提出了一个类似的问题:LINK 但不幸的是,我错过了将答案实施到我的案例中。
这是类组件:
import React from "react";
class GoogleAuth extends React.Component {
componentDidMount() {
window.gapi.load("client: auth2", () => {
window.gapi.client
.init({
clientId: "myVerySecretAPI",
scope: "email"
})
.then(() => {
this.auth = window.gapi.auth2.getAuthInstance(); //this gets me acces to the auth object
this.setState({ isSignedIn: this.auth.isSignedIn.get() });
});
});
}
renderAuthButton() {
if (this.state.isSignedIn === null) {
return <div>I dont know if we are signed in</div>;
} else if (this.state.isSignedIn) {
return <div>I am signed in!</div>;
} else {
return <div>I am not signed in</div>;
}
}
render() {
return <div>{this.renderAuthButton()}</div>;
}
}
export default GoogleAuth;
这是我重构的代码:
import React, { useEffect, useState } from "react";
const GoogleAuth = () => {
const [ auth, setAuth ] = useState(null);
useEffect(
() => {
window.gapi.load("client:auth2", () => {
window.gapi.client
.init({
clientId: "834243588921-gob95b7q7n3eids3fm8du8oharkv5od0.apps.googleusercontent.com",
scope: "email"
})
.then(() => {
setAuth(window.gapi.auth2.getAuthInstance());
auth({ isSignedIn: setAuth.isSignedIn.get() }); // this is the line where I get an error (please see below)
});
});
},
[ auth ]
);
const renderAuthButton = (isSignedIn) => {
if (isSignedIn === null) {
return <div>I dont know if we are signed in</div>;
} else if (isSignedIn) {
return <div>I am signed in!</div>;
} else {
return <div>I am not signed in</div>;
}
};
return <div>{renderAuthButton()}</div>;
};
export default GoogleAuth;
我在 chrome 中收到一个错误,说:
Uncaught TypeError: Cannot read property 'get' of undefined at GoogleAuth.js:16
我知道,我遗漏了一些小东西来了解钩子的使用。 欢迎任何帮助!
【问题讨论】:
标签: reactjs oauth oauth-2.0 react-hooks google-api-js-client