gpt4 book ai didi

reactjs - 将基于类的组件转换为 Hook (gapi API)

转载 作者:行者123 更新时间:2023-12-05 03:01:19 26 4
gpt4 key购买 nike

我有一个基于类的组件,它使用 gapi (Google Auth) API 呈现一个按钮并且它可以工作:

import React from 'react';

class GoogleAuth extends React.Component {
state = { isSignedIn: null };

componentDidMount() {
window.gapi.load('client:auth2', () => {
window.gapi.client
.init({
clientId: process.env.REACT_APP_CLIENT_ID,
scope: 'email',
})
.then(() => {
this.auth = window.gapi.auth2.getAuthInstance();
this.handleAuthChange();
this.auth.isSignedIn.listen(this.handleAuthChange);
});
});
}

handleAuthChange = () => {
this.setState({ isSignedIn: this.auth.isSignedIn.get() });
};

handleSignIn = () => {
this.auth.signIn();
};

handleSignOut = () => {
this.auth.signOut();
};

renderAuthButton() {
if (this.state.isSignedIn === null) {
return null;
} else if (this.state.isSignedIn) {
return <button onClick={this.handleSignOut}>Sign Out</button>;
} else {
return <button onClick={this.handleSignIn}>Sign in with Google</button>;
}
}

render() {
return <div>{this.renderAuthButton()}</div>;
}
}

export default GoogleAuth;

我很难尝试将其转换为使用 Hook 。主要问题是 this.auth...这就是类如何引用 window.gapi.auth2.getAuthInstance()

我已经尝试了很多不同的方法,包括将身份验证保持在以下状态:

export default function GoogleAuth() {
const [isSignedIn, setIsSignedIn] = useState(null);
const [auth, setAuth] = useState(null);
useEffect(() => {
window.gapi.load('client:auth2', () => {
window.gapi.client
.init({
clientId: process.env.REACT_APP_CLIENT_ID,
scope: 'email',
})
.then(() => {
setAuth(window.gapi.auth2.getAuthInstance());
setIsSignedIn(auth.isSignedIn.get());
auth.isSignedIn.listen(() => setIsSignedIn(auth.isSignedIn.get()));
});
});
}, [auth]);

最佳答案

仅仅 8 个月后,请像下面那样尝试使用带有身份验证的 useRef。它对我有用。

   const GoogleAuth  = () => {
const [isSignedIn, setSignedIn] = useState(null)
const auth = useRef(null);
useEffect(() => {
window.gapi.load('client:auth2', () => {
window.gapi.client.init({
clientId:
'jcu.apps.googleusercontent.com',
scope: 'email'
}).then(() => {
auth.current = window.gapi.auth2.getAuthInstance();
setSignedIn(auth.current.isSignedIn.get());
auth.current.isSignedIn.listen(onAuthChange)
});
});
}, [isSignedIn]);

const onAuthChange = () => {
setSignedIn(auth.current.isSignedIn.get())
}

if (isSignedIn === null) {
return (
<div>I don't 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>);
}
}

关于reactjs - 将基于类的组件转换为 Hook (gapi API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55961293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com