【问题标题】:property 'photos' does not exist on type 'Image[]'类型“图像 []”上不存在属性“照片”
【发布时间】:2021-12-26 02:34:51
【问题描述】:

我正在尝试从 pexels api 获取图片的响应,而我想要做的是填充我从响应中获得的照片对象的 defaultImages 空数组。

import * as React from "react";
import { ChakraProvider} from "@chakra-ui/provider";
import {theme} from "@chakra-ui/theme";
import {Text,Box} from "@chakra-ui/react";
import axios from 'axios';



const App = () => {
 
  return (
   <ChakraProvider theme={theme}>
     <Box>
     <Display/>
     </Box>
   </ChakraProvider>
  );
}

export default App;


interface Image {
  id:number,
  width:number,
  height:number,
  avg_color:string,
  liked:boolean,
  photographer:string,
  photographer_id:number,
  photographer_url:string,
  src:object,
}


const defaultImages : Image[] = [];


function Display() {
  const [Images,setImages] : [Image[], (images: Image[]) => void] = React.useState(defaultImages);
  const [loading,isLoading] : [boolean,(loading: boolean) => void] = React.useState<boolean>(true);
  const [error,setError] : [string,(error: string) => void] = React.useState("");
  React.useEffect(() => {
    axios.get<Image[]>('https://api.pexels.com/v1/curated?page=2&per_page=40', {
      headers: {
        Authorization : '563492ad6f91700***********************************'
      },
    }).then(response => {
      setImages(response.data.photos);
      isLoading(false);
      console.log("it worked!",response.data.photos);
    }).catch(ex => {
      const error = ex.response.status === 404 ? 'Page not found':'Something wrong has happened';
      setError(error);
      isLoading(false);
      console.log(error);
    })
  },[]);

  return (
    <Text></Text>
  );
}

我得到了很好的响应数据,当我在 (response.data) 之后添加“.photos”访问器时,对象数组显示在控制台上,但我收到错误 Uncaught (in promise) TypeError: ex.response is undefined

我不明白这里有什么问题。我尝试在 Image 界面上显式添加“照片”数组属性,但仍然出现相同的错误。

【问题讨论】:

  • Image[] 是一个 array,它确实没有 photos 属性。

标签: javascript reactjs typescript axios


【解决方案1】:

Uncaught (in promise) TypeError: ex.response is undefined 错误只是告诉您ex 对象没有定义响应字段。它与您正确实现的照片数组无关。

这是您尝试访问请求的响应的结果,该响应当前不存在。例如,如果发出了请求,但没有收到来自服务器的响应,就会发生这种情况。

为确保仅检查响应的错误代码(如果存在),请将代码包装在 if 语句中以检查响应是否已设置。

试试这个:

}).catch(ex => {
      if(ex.response) {
          const error = ex.response.status === 404 ? 'Page not found':'Something wrong has happened';
          setError(error);
          isLoading(false);
          console.log(error);     
      }
  })

您可以在the axios documentation 中找到更多错误处理示例。

我的小红利专业提示:调用您的变量 error 而不是 ex 并将 error 重命名为 errorMessage 使您的代码更易于阅读和理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-11
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 2021-12-03
    • 2021-07-10
    相关资源
    最近更新 更多