【问题标题】:React parsing JSON data with multiple worded identifierReact 使用多字标识符解析 JSON 数据
【发布时间】:2020-07-16 00:03:19
【问题描述】:

我正在尝试访问 JSON 数据,但是 JSON 标识符使用多个单词。 JSON 数据的格式如下:

    "Meta Data": {
        "1. Information": "Intraday (5min) open, high, low, close prices and volume",
        "2. Symbol": "IBM",
        "3. Last Refreshed": "2020-04-02 16:00:00",
        "4. Interval": "5min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (5min)": {
        "2020-04-02 16:00:00": {
            "1. open": "109.5600",
            "2. high": "110.3200",
            "3. low": "109.4300",
            "4. close": "110.0400",
            "5. volume": "421231"
        },
//...

我使用:

componentDidMount() {
    fetch('https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo')
    .then(res => res.json())
    .then((data) => {
      this.setState({ StockInfo: data })
    })
    .catch(console.log)
  }

获取数据。

console.log(StockInfo["Meta Data"])

这一行可以用来访问数据,但是

console.log(StockInfo["Meta Data"]["1. Information"]

我收到错误:TypeError:无法读取属性 '1。未定义的信息。还有,

console.log(StockInfo[0]) //or
console.log(StockInfo["Meta Data"][0]

也会出现同样的错误。

【问题讨论】:

  • 你在哪里记录这些?

标签: javascript json reactjs jsx


【解决方案1】:

您正在变得未定义,因为在 componentDidMount 之前调用了渲染函数,并且您正在进行异步调用。所以在渲染中检查它是否可用。

 render() {
    if (!this.state.StockInfo["Meta Data"]) {
      return null;
    }
    return (
      <div>
         {this.state.StockInfo["Meta Data"]["1. Information"]}
      </div>
    );
  } 

Stackblitz:https://stackblitz.com/edit/react-dnzze3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多