Доступ к вложенному объекту - ReactJs - PullRequest
0 голосов
/ 28 марта 2020

Я пытаюсь проанализировать и отобразить вложенный объект, который выглядит следующим образом:

{
  "country": "germany",
  "timeline": {
    "cases": {
      "1/22/20": 0,
      "1/23/20": 0,
      "1/24/20": 0,
      "1/25/20": 0,
      "1/26/20": 0,
      "1/27/20": 1,
      "1/28/20": 4,
      "1/29/20": 4,
      "1/30/20": 4
    }
  }
}

Это моя первая попытка, где я попробовал несколько вариантов вставки ответа в компонент.

import React, { Component } from 'react'

class Chart extends Component {
  state = {
    historyStats: [],
    // error: true
  };

  componentDidMount() {
    fetch('https://corona.lmao.ninja/v2/historical/germany')
    .then(res => res.json())
    .then((data) => {
      this.setState({ historyStats: data })
    })
    .catch(console.log)
  }

  render() {
    const {historyStats} = this.state;
    console.log(Object.values(historyStats));

    return (
      <div>

       {Object.values(historyStats).map(test => (
        <p>{test[0]} | {test[1]}</p>
      ))}
      </div>
    )
  }
}


export default Chart;

Как мне получить результат, подобный следующему:

test [0]} = 1/22/20 - Дата

test [ 1] = 0 - Значение

Помощь оценена Спасибо

1 Ответ

0 голосов
/ 28 марта 2020

хорошо, проблема в том, что вы неправильно обращаетесь к своим элементам, и вы определяете historyStats как массив, но ответ - это объект, в идеале, лучше всего преобразовать данные в то, что вы хотите. давайте сделаем это.

также позволяет использовать объектные записи , чтобы получить наши [key, value]

import React, { Component } from 'react'

class Chart extends Component {
  state = {
    historyStats: [],
    // error: true
  };

  componentDidMount() {
    fetch('https://corona.lmao.ninja/v2/historical/germany')
    .then(res => res.json())
    .then((data) => {
      // basically, lets get what it is important, the CASES.
      const { timeline } = data;
      const { cases } = timeline;

      // now cases is an object, lets transform it into an array of 2 entries, the key and value.
      const newHistoryStats = Object.entries(cases).map(pair=> pair);
      this.setState({ historyStats: newHistoryStats })

    })
    .catch(console.log)
  }

  render() {
    const {historyStats} = this.state;
    console.log(Object.values(historyStats));

    return (
      <div>
        {
          historyStats.map(test => ( <p>{test[0]} | {test[1]}</p> ))
        }
      </div>
    )
  }
}


export default Chart;

, в основном мы создаем такие записи:

fetch('https://corona.lmao.ninja/v2/historical/germany')
  .then(res => res.json())
  .then((data) => {
    // basically, lets get what it is important, the CASES.
    const { timeline } = data;
    const { cases } = timeline;

    // now cases is an object, lets transform it into an array of 2 entries, the key and value.
    const newHistoryStats = Object.entries(cases).map(pair => pair);
    
    // this will be similar to the render
    newHistoryStats.map(test => console.log(test[0], "|", test[1]))
  })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...