【问题标题】:Error: Objects are not valid as a React child (Axios and openweathermap API)错误:对象作为 React 子项无效(Axios 和 openweathermap API)
【发布时间】:2019-04-17 01:22:25
【问题描述】:

我正在尝试渲染从 openweathermap 获取的数据,但我不断收到以下错误:

对象作为 React 子对象无效(发现:对象带有键 {coord, weather, base, main, visibility, wind, clouds, dt, sys, id, name, cod})。如果您打算渲染一组子项,请改用数组。

import React from 'react';
import axios from 'axios';

class PersonList extends React.Component {
  state = {
    persons: []
  };

  componentDidMount() {
    axios
      .get(
        `https://api.openweathermap.org/data/2.5/weather?q=Toronto&appid=abdeb978cd944502164274a08638f7ac`
      )
      .then(res => {
        const persons = res.data;
        this.setState({ persons });
      });
  }

  render() {
    return <div>{this.state.persons}</div>;
  }
}

export default PersonList;

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    首先,将json从响应转化为对象

      componentDidMount() {
        axios.get(`https://api.openweathermap.org/data/2.5/weather?q=Toronto&appid=abdeb978cd944502164274a08638f7ac`)
          .then(res => res.json())
          .then(res => {
            const persons = res.data;
            this.setState({ persons });
          })
      }
    

    其次,Objects are not valid as a React child (found: object with keys {coord, weather, base, main, visibility, wind, clouds, dt, sys, id, name, cod}) 表示{ this.state.persons } 是实际对象,具有coordweatherbasemainvisibilitywindclouds、@9876 属性、sysidnamecod。而且你不能渲染一个对象。

    要查看对象中的内容,您可以执行以下操作

      render() {
        return (
          <div>
             { JSON.stringify(this.state.persons) }
          </div>
        );
      }
    

    这会将对象转换为字符串,您可以渲染字符串,这样您就可以看到this.state.persons 中的所有内容。

    现在您需要向我们提供您想用这些数据做什么,因为有很多属性要显示,而且您可以用它做很多事情。

    编辑:正如cmets中所说,要渲染weather,您可以这样做

      render() {
        return (
          <div>
             { this.state.persons.weather }
          </div>
        );
      }
    

    但是你需要确定weather是一个字符串,否则会导致同样的错误。

    另外,您需要将persons 的初始状态更改为一个对象(也许您也应该重命名该变量)。

    改变这个:

    state = {
        persons: []
    }
    

    对此:

    state = {
        persons: {}
    }
    

    您还可以检查this.state.persons 是否不是一个空对象,然后再从它进行渲染。

    【讨论】:

    • 谢谢!我只想在“天气”中显示数据。具体描述。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2021-08-20
    • 2021-06-04
    相关资源
    最近更新 更多