【问题标题】:ReactJS/Javascript: Map function and JSONReactJS/Javascript:映射函数和 JSON
【发布时间】:2019-01-31 13:21:38
【问题描述】:

在控制台中,数据加载了一个我试图渲染的 JSON 文件(见下文)。来自 Chrome 的错误消息是 TypeError: data.map is not a function。我没有找到 d3.extent 函数的好例子,所以我在这里寻求一些帮助。 Graph 组件如下所示:

constructor({data=[]}) {
  console.log('construc data:', data)
    const times = d3.extent(data.map(action => action.timestamp))
    const range = [50, 450]
    super({data})
    this.state = {data, times, range}
}

JSON 文件:

{data: 
     action: 
        {action: [{action: "Changed", timestamp: 1499348050,…},…]}

【问题讨论】:

  • 您包含的 JSON sn-p 不是有效的 JSON。
  • 那么如何使用 d3.extent 解析它呢?
  • 我想我需要做一个嵌套的 d3.extent?如果是这样,不要用它来完成它。到目前为止,所有在线示例都有平面 JSON/Arrays。
  • 试试data.action.action.map(action => . . .)
  • 地图功能不适用于对象。与数组相关的映射函数。

标签: javascript reactjs graphql-js map-function


【解决方案1】:

JSON 不正确

您的 JSON 文件无效,因为您的密钥需要用引号引起来。使用JSON Validator 确保您拥有正确的 JSON 文件。


Object 上调用.map() 会导致TypeError

当您的数据从 JSON 文件加载时(并且不默认为构造函数设置的空数组),请确保它的形状为 Array,因为在 @ 上调用 .map() 方法987654330@ 而不是Array 会导致TypeError。这是因为.map()Array 原型的一部分,而d3.extent(array) 需要Array 作为参数。

阅读更多关于 JavaScript 的 Array

阅读更多关于 JavaScript 的Object


正确的方法

如果您的 JSON 已正确加载到 data 对象中,则以下操作应该有效:

d3.extent(data.action.action.map(action => action.timestamp))

【讨论】:

    猜你喜欢
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2011-08-04
    • 2018-12-04
    • 1970-01-01
    • 2020-04-12
    • 2020-08-14
    相关资源
    最近更新 更多