对于 google oauth,无法在回调内调用 React Hook“useState”

问题描述 投票:0回答:1

尝试使用google oauth,我很难将其与react集成:

import { useEffect, useState } from "react";
import { jwtDecode } from "jwt-decode";

function App() {

  useEffect(() => {
    const [jwt, setJwt] = useState({});

    /* global google */
    google.accounts.id.initialize({
      client_id: '771696799412-ukeqmbm6gsi99n0aial8g8l8d107uak2.apps.googleusercontent.com',
      callback: handleCallbackResponse
    });

    google.accounts.id.renderButton(
      document.getElementById('signInDiv'),
      {
        theme: 'outline',
        size: 'large'
      }
    );
  }, [])

  function handleCallbackResponse(response) {
    setJwt(response.credential);
  }

  return (
    <>
      <div id="signInDiv"></div>
      {jwt ? (
        <div>logged in</div>
      ) : (
        <div>not logged in</div>
      )}
    </>
  );
}

export default App;

正在给我

Line 7:27:  React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

第 25:5 行:“setJwt”未定义

我知道setStates不能等到用户使用google登录,但是如何存储身份验证?

reactjs oauth google-oauth setstate
1个回答
0
投票

尝试按照错误提示执行操作

function App() {
    const [jwt, setJwt] = useState({});
    useEffect(...)
...
© www.soinside.com 2019 - 2024. All rights reserved.