reactjs 未捕获的类型错误:无法析构"response.profileObj"的属性"name",因为它未定义

qq24tv8q  于 2023-02-03  发布在  React
关注(0)|答案(4)|浏览(119)
const navigate = useNavigate();

const responseGoogle = (response) => {

  localStorage.setItem('user', JSON.stringify(response.profileObj));

  const { name, googleId, imageUrl } = response.profileObj;

  const doc = {
    _id: googleId,
    _type: 'user',
    userName: name,
    image: imageUrl,
  };

  client.createIfNotExists(doc).then(() => {
    navigate('/', { replace: true });
  });
};

我得到一个错误“name is undefined”--但是怎么会这样呢?name有什么问题吗?我已经处理这个问题很长时间了,但是我仍然不能弄清楚

qnzebej0

qnzebej01#

我遇到了同样的问题。我通过安装和一个额外的包解决了它:

npm install gapi-script

我在我的代码中导入了它:

import { gapi } from "gapi-script"

我还从react中导入了useEffect:

import { useEffect } from "react"

然后我定义了一个函数并包含了我的clientId。我的代码实现的片段如下所示:

import React, { useEffect } from "react";
import GoogleLogin from "react-google-login";
import { useNavigate } from "react-router-dom";
import { gapi } from "gapi-script";
import { FcGoogle } from "react-icons/fc";

import { client } from "../client";

function Login() {

  const clientId =
    "360735963044-**********1l8rgmacmsmr9p4la9b47.apps.googleusercontent.com";

  useEffect(() => {
    const initClient = () => {
      gapi.client.init({
        clientId: clientId,
        scope: "",
      });
    };
    gapi.load("client:auth2", initClient);
  });

  const navigate = useNavigate();

  const responseGoogle = (response) => {
    localStorage.setItem("user", JSON.stringify(response.profileObj));
    const { name, googleId, imageUrl } = response.profileObj;
    const doc = {
      _id: googleId,
      _type: "user",
      userName: name,
      image: imageUrl,
    };
    client.createIfNotExists(doc).then(() => {
      navigate("/", { replace: true });
    });
  };

希望对你有用!

wb1gzix0

wb1gzix02#

谷歌回应有3种回应类型。成功回应:GoogleLoginResponse | GoogleLoginResponseOffline,故障响应时:error.
profileObj只存在于GoogleLoginResponse类型上。因此,如果你有其他响应类型,profileObj将是未定义的,并且你不能解构名称。
你必须控制它。

export interface GoogleLoginProps {
  readonly onSuccess?: (response: GoogleLoginResponse | GoogleLoginResponseOffline) => void,
  readonly onFailure?: (error: any) => void,
  //...
}
// Based on https://developers.google.com/identity/sign-in/web/reference
export interface GoogleLoginResponse {
  getBasicProfile(): BasicProfile;
  getAuthResponse(includeAuthorizationData?: boolean): AuthResponse;
  reloadAuthResponse(): Promise<AuthResponse>;
  getGrantedScopes(): string;
  getHostedDomain(): string;
  getId(): string;
  isSignedIn(): boolean;
  hasGrantedScopes(scopes: string): boolean;
  disconnect(): void;
  grantOfflineAccess(options: GrantOfflineAccessOptions): Promise<GoogleLoginResponseOffline>;
  signIn(options: SignInOptions): Promise<any>;
  grant(options: SignInOptions): Promise<any>;
  // google-login.js sez: offer renamed response keys to names that match use
  googleId: string;
  tokenObj: AuthResponse;
  tokenId: string;
  accessToken: string;
  readonly code?: string;//does not exist but here to satisfy typescript compatibility
  profileObj: {
    googleId: string;
    imageUrl: string;
    email: string;
    name: string;
    givenName: string;
    familyName: string;
  }
}
export interface GoogleLoginResponseOffline {
  readonly code: string;
}
pobjuy32

pobjuy323#

小Pig倒车的o. c回答:
Google响应有3种响应类型:GoogleLoginResponse、GoogleLoginResponse脱机或错误。只有GoogleLoginResponse具有配置文件对象属性。
可能需要更改以下行:

const { name, googleId, imageUrl } = response.profileObj;

到下面将有助于避免崩溃:

const { name, googleId, imageUrl } = response.profileObj ?? {};

你仍然需要用其他方法来解决潜在的问题,但是空合并可以阻止崩溃。

ilmyapht

ilmyapht4#

你必须等待来自响应的名称。我这样做了,它起作用了。

const navigate = useNavigate();
  const responseGoogle = (response) => {
    if (!response.profileObj) return;
    localStorage.setItem('user', JSON.stringify(response.profileObj));
    const { name, googleId, imageUrl } = response.profileObj;

    const doc = {
      _id: googleId,
      _type: 'user',
      userName: name,
      image: imageUrl,
    };

    client.createIfNotExists(doc).then(() => {
      navigate('/', { replace: true });
    });
  };

相关问题