Обработка объектов данных JSON в React - PullRequest
0 голосов
/ 07 ноября 2019

Не могу понять, как извлечь данные из проанализированного и сохраненного объекта json из состояния ... Я пробовал много способов, но получаю ошибки (данные из openweathermap)

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: true,
      data: null
    };
  }
  getWeather(url) {
    fetch(url)
        .then(res => res.json())
        .then(data =>
            this.setState({
              isLoading: false,
              data: data
            })
        )
        .catch(error => console.log("Error Loading data " + error));
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(position => {
      const url = `${API}lat=${position.coords.latitude}&lon=${position.coords.longitude}&${APPID}`;
      this.getWeather(url);
    });
  }

  render() {

    return (
        <div>
          {console.log(this.state.data)}
          {/*renders json*/}
          <h1>{this.state.data.name}</h1>
        </div>
    );
  }
}

1 Ответ

0 голосов
/ 07 ноября 2019

Я полагаю, вы можете получить cannot read property 'name' of null. Не уверен насчет точной ошибки, но что-то в этом роде.

Попробуйте использовать

<h1>{ this.state.data && this.state.data.name }</h1>

Пока API времени не дает ответ, ваши данные в состоянии null, поэтому выне может получить доступ data.name.

...