【问题标题】:How to handle response from API with TypeScript如何使用 TypeScript 处理来自 API 的响应
【发布时间】:2021-03-26 03:04:49
【问题描述】:

使用带有 TypeScript 的 Axios 处理来自 HTTP 请求的响应时遇到问题。我不明白我看到的行为。这会返回一次位置,然后当我刷新页面时它再次不起作用,它说 TypeError: Cannot read property 'location' of undefined 我感觉我不明白这一切是如何工作的。

我要做的就是访问从 API 返回的所有数据。如果有人有使用 TypeScript 的简单示例,我将不胜感激。我可以在普通的 JavaScript 中执行此操作,但无法将其转换为 TypeScript。我的问题类似于这个post

const Webmap: FC = () => {
  const url = 'https://data.police.uk/api/crimes-street/all-crime?lat=52.629729&lng=-1.131592&date=2019-10';

  interface User {
    id?: any;
    location?: any;
}

  const [users, setUserList] = useState<User[]>([]);
  useEffect(() => {
    axios.get<User[]>(url)
      .then(response => {
        // console.log(response.data);
        setUserList(response.data);
      });
  }, [])

   console.log(users[0].location)

【问题讨论】:

  • 请记住,所有 JavaScript 也是有效的 TypeScript。如果您在 JavaScript 中有一个有效的解决方案,那么它也可以用作 TypeScript 中的一个有效解决方案。因此,这些情况下的问题通常是一些拼写错误/复制粘贴错误。
  • @AlexWalker 好吧,我在 JavaScript 中使用的解决方案没有使用 Axios,而是使用了 swr。我遇到了这个 const fetcher = (...args) => fetch(...args).then(response => response.json()); 的问题TypeScript 抱怨 Expected 1-2 arguments,但得到了 0 个或更多。 TS2556 我不知道如何解决这个错误,所以我正在尝试另一种解决方案。

标签: javascript reactjs typescript axios


【解决方案1】:

在调用setUserList 填充数组之前,users[0] 是什么?这是undefined。也许您应该在尝试访问其字段之前检查users[0] 是否为非空值?

如果是我,我会useState 调用提供默认值:

const [users, setUserList] = useState<User[]>();

这意味着users 的类型将是User[] | undefined。在发出 Web 请求之前,users 的类型将为 undefined

现在,当您想使用它时,您可以判断它是否已被填充,因为检查 users 是否为非空

if(users != null){
    // users is definitely populated from the web request
    // although the array may contain no items
    users.forEach(u => console.log(u));
}

...或...在 JSX/TSX 中

{users && users.map(u => (<div>{u.location}</div>)}

narrowusers的类型从User[] | undefined变为User[]

在尝试引用它们的属性之前,您仍然需要确保在此之后显式访问的索引(例如 users[0]实际上存在。

【讨论】:

    【解决方案2】:

    这是由于您试图访问数据,即使它没有设置在状态。

    如果用户是not emptytruthy,则记录数据。

    if(users && users.length > 0)){
        console.log(users.location)
    }
    

    【讨论】:

    • 您的测试将始终通过并且错误将持续存在。 users 没有定义为数组。请参阅上面传递给setState 的默认值。
    • 是的,我刚刚尝试添加该 if 语句,但它仍然给出相同的错误。
    • 道歉@spender 指出你一开始有一个空数组。所以我更新了答案以检查数组是否为空,然后只有 console.log() 的值。
    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2013-08-27
    • 2015-01-26
    • 2021-03-30
    • 1970-01-01
    相关资源
    最近更新 更多