我可以使用this.auth将其与类组件一起使用,但如何使用基于功能的组件和挂钩来实现这一点
import React, { useEffect, useState } from 'react';
const GoogleAuth = () => {
const [ isSignedIn, setIsSignedIn ] = useState(null);
useEffect(() => {
window.gapi.load('client:auth2', () => {
window.gapi.client
.init({
clientId: '#ID',
scope: 'email'
})
.then(() => {
//THIS AUTH VARIABLE
const auth = window.gapi.auth2.getAuthInstance();
setIsSignedIn(window.gapi.auth2.getAuthInstance().isSignedIn.get());
auth.isSignedIn.listen(onAuthChange);
});
});
}, []);
const onAuthChange = () => {
setIsSignedIn(window.gapi.auth2.getAuthInstance().isSignedIn.get());
};
this.auth
的挂钩等价物将是useRef
:
import React, { useEffect, useState, useRef } from 'react';
const GoogleAuth = () => {
const auth = useRef()
const [ isSignedIn, setIsSignedIn ] = useState(null);
useEffect(() => {
window.gapi.load('client:auth2', () => {
window.gapi.client
.init({
clientId: '#ID',
scope: 'email'
})
.then(() => {
auth.current = window.gapi.auth2.getAuthInstance();
setIsSignedIn(window.gapi.auth2.getAuthInstance().isSignedIn.get());
auth.current.isSignedIn.listen(onAuthChange);
});
});
}, []);
const onAuthChange = () => {
setIsSignedIn(window.gapi.auth2.getAuthInstance().isSignedIn.get());
};
然而,由于这是身份验证数据,您可能也有兴趣查看useContext
,或者可能有一个自定义挂钩将其存储在sessionStorage或localStorage中。