【问题标题】:Type script react Json array formatting to display打字稿反应Json数组格式显示
【发布时间】:2019-06-22 10:48:07
【问题描述】:

这是存储在数据库中的数据

[
  {
    "id": "0",
    "item": {
      "title": "City1"
    }
  },
  {
    "id": "1",
    "item": {
      "title": "City2"
    }
  }
]

现在这些数据存在于 props 中的 city 中。

现在数据处于从数据库加载的状态中反应

interface itemType { title: string };

声明的用于格式化字符串数据的接口, 我只想以字符串格式显示标题。

我正在写一个这样的函数。

private loadData = () => {
        interface itemType { title: string };   
        const titleArray: [itemType] = [];
        const { city} = this.props;
        city.source.isComplete ? city.source.value.map((item) => {
            titleArray.push({ title: item.title })

        }) : [];
    }

按照上面的要求帮我把它转换成字符串。谢谢。

我只想从 JSON 数组中取出标题并将其存储在变量中。 我怎样才能做到这一点? 谢谢

【问题讨论】:

    标签: javascript arrays json reactjs typescript


    【解决方案1】:

    您可以直接映射您获取的数据:

    const titleArray: [itemType] = city.source.value.map(item => item.title);
    

    【讨论】:

    • 类型 'Value[]' 不可分配给类型 '[itemType]'。 “值 []”类型中缺少属性“0”。发生此错误。
    • 类型“[]”不可分配给类型“[itemType]”。类型“[]”中缺少属性“0”。还有这个
    • 你为什么不使用 strings 的数组?而不是itemType
    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 2019-07-11
    • 2022-11-19
    • 2021-03-21
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多