简体   繁体   English

React:如何解决错误:Object is of type 'unknown'?

[英]React: How to solve the error: Object is of type 'unknown'?

I'm trying to use the axios in order to fetch data from an API, but the response.data gives me 'unknown' error.我正在尝试使用 axios 从 API 获取数据,但 response.data 给出了“未知”错误。 Not sure how to fix this.不知道如何解决这个问题。 Anyone can help me please.任何人都可以帮助我。 I'm using Typescript.我正在使用 Typescript。

This is the error I'm getting:这是我得到的错误:

Object is of type 'unknown'.ts(2571) (parameter) response: AxiosResponse<unknown, any> Object 是 'unknown'.ts(2571) 类型(参数) response: AxiosResponse<unknown, any>

    interface Props {
  pokemonItem: PokemonItem[];
  children: React.ReactNode | React.ReactNode[];
}

export const PokemonContainer: React.FC = (props) => {
  const { pokemonItem } = props;
  const { name, height, weight, abilities } = pokemonItem;

  const [hovered, setHovered] = React.useState(false);
  const [imageLoaded, setImageLoaded] = React.useState(false);
  const [pokemon, setPokemon] = React.useState([]);


  const getPokemons = () => {
    try {
      axios
      .get('https:pokeapi.co/api/v2/pokemon')
      .then((response) => {
        setPokemon(response.data.results.map((item) => item.name));
      });
    } catch (error) {
      console.log(error);
    }
  };

  React.useEffect(() => {
    getPokemons();
  }, []);

in another file I have defined the data types:在另一个文件中我定义了数据类型:

export interface PokemonItem {
id: number;
name: string;
height: string;
weight: string;
abilities: string;
image: string;
}

response type is unknown to TS. TS unknown response类型。 unknown is just a like any in the way that it can be anything, but is a safer option to it. unknown就像any一样,它可以是任何东西,但它是一个更安全的选择。 TS will not let you access response properties since it has no idea what the object might be. TS 不会让您访问response属性,因为它不知道对象可能是什么。

You will want to try this and use it as any .您会想尝试这个并将其用作any .

const getPokemons = () => {
    try {
      axios
      .get('https:pokeapi.co/api/v2/pokemon')
      .then((response : any) => { 
       setPokemon(response.data.results.map((item) => item.name));
      });
    } catch (error) {
      console.log(error);
    }
  };


I have the same problem using Fetch, and the way I solved it is: create a new type for the "error" of "unknown" type.我在使用 Fetch 时遇到了同样的问题,我解决它的方法是:为“未知”类型的“错误”创建一个新类型。

type ResponseData = {
  id: string;
  token: string;
  error: string;
};

interface ErrorRes {
  json: () => Promise<ResponseData>;
}

export const handleSignIn = async (
  email: string,
  password: string,
): Promise<ResponseData> => {
  try {
    const response = await fetch('https://reqres.in/api/login', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email, password }),
    });
    return (await response.json()) as ResponseData;
  } catch (error) {
    return await (error as ErrorRes).json();
  }
};

If you still need an Axios solution without turning off TypeScript, here it is:如果在不关闭TypeScript的情况下还需要Axios解决方案,这里是:

export interface ErrorResponseData {
  message: string
}

try {
      const { data } = await axios.post('login', payload)
      return data
    } catch (e) {
      return (e as AxiosError<Array<ErrorResponseData>>).response?.data[0].message || ERROR_SOMETHING_WENT_WRONG
    }

The AxiosError type is a Generic that takes in the expected error response interface. AxiosError类型是一个 Generic,它接受预期的错误响应接口。

Of course, the interface should match your expected error format.当然,界面应该符合您预期的错误格式。 In my case, I always receive an array of errors, but I am only interested in the first error.就我而言,我总是收到一系列错误,但我只对第一个错误感兴趣。 I then added a fallback error in case the error received doesn't match the shape, eg.network error.然后我添加了一个回退错误,以防收到的错误与形状不匹配,例如网络错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM