【问题标题】:TypeScript: how to find an object in an array and return that specific object?TypeScript:如何在数组中查找对象并返回该特定对象?
【发布时间】:2021-05-05 08:04:11
【问题描述】:

我正在尝试在数组中查找一个对象并返回该特定对象。我是打字稿的新手,所以我尝试用这种方式解决它,但我不确定它为什么不起作用。

已编辑:我的代码甚至没有被编译!我收到以下错误:

/Users/.../api/VaccineDataApi.tsx(64,14) 中的 TypeScript 错误: 对象可能是“未定义的”。 TS2532

import React, { useEffect, useState } from 'react';
import axios from 'axios';

type VaccineDataState = {
    Date: Date,
    Location: string, //Location is state Abbreviations like 'WA'
    LongName: string,
    Doses_Distributed: number,
}

const VaccineData = () => {
    const [vaccine, SetVaccine] = useState<VaccineDataState[]>([])
    const [errorMessage,SetErrorMessage] = useState(null)

    useEffect(() => {
        axios.get("https://localhost:3000")
        .then((response) => {
            const apiVaccineData = response.data.vaccination_data;
            SetVaccine(apiVaccineData);
        })
        .catch((error) => {
            SetErrorMessage(error.message);
            console.log(errorMessage);
        })
    }, []);

  
    let vaccineData = vaccine.find(state => state.Location === 'WA');

    return(
        <div>
            <p>test</p>
            {vaccineData.Location}
        </div>
    )
    
};

export default VaccineData;

【问题讨论】:

  • 这看起来是对的,console.log(vaccine); 时你会得到什么?
  • 我不能,因为它甚至没有编译:这是错误消息:“()=>元素”类型上不存在属性“位置”。 TS2339
  • 好的,所以问题不是描述你遇到什么样的错误,更新它
  • 我现在就做,谢谢@Kalhan.Toress

标签: reactjs typescript object find


【解决方案1】:

VaccineData 指的是功能组件。您可能想要vaccineData.Location 而不是VaccineData.Location

编辑:要修复 let vaccineData: VaccineDataState | undefined Object is possibly 'undefined',您可以:

添加 ! 以告诉 Typescript 编译器 vaccineData 永远不会是 undefined(只有当您确定它实际上永远不会是时):

let vaccineData = vaccine.find(state =&gt; state.Location === 'WA')!;

添加一些代码来检查undefined

    let vaccineData = vaccine.find(state => state.Location === 'WA');
    if(!vaccineData)
        return <p>Data not found!</p>;

【讨论】:

  • 我试过了,但后来我遇到了这个错误'让疫苗数据:疫苗数据状态 | undefined Object 可能是 'undefined'.ts(2532)'
  • @Nr 没错。 find 返回一个可选值。试试条件句。
  • @tmwilliamlin168 你的回答解决了!非常感谢你帮助我!
  • 你是对的@Christopher 我应该注意到这一点
猜你喜欢
  • 2019-06-14
  • 1970-01-01
  • 2017-07-22
  • 2010-11-12
  • 1970-01-01
  • 2013-03-27
  • 2017-02-02
  • 2018-09-24
  • 2016-08-10
相关资源
最近更新 更多