在功能性 React 组件中使用 google api

Using google api in a functional react component

let [auth, setAuth] = useState(null);

    useEffect(() => {
        window.gapi.load('client:auth2', () => { 
            window.gapi.client.init({
                clientId: 'xxx.apps.googleusercontent.com',
                scope: 'email'
            }).then(() => {
                setAuth(window.gapi.auth2.getAuthInstance());
                onAuthChange(auth.isSignedIn.get());
                auth.isSignedIn.listen(onAuthChange);
            });
        });
    }, []);

我正在使用 Google 的 api 进行身份验证:

https://apis.google.com/js/api.js

我尝试使用 useState 将我的 class 组件重构为功能组件,但是当使用 setAuth 分配 window.gapi.auth2.getAuthInstance() 返回的值时,我得到 null在授权里面。 setAuth 未按预期运行是否有原因?

我在下一行收到以下错误:

类型错误:auth 为空

那是因为 auth 的值在下一次渲染之前对您的功能组件不可用。