【问题标题】:'Error: Objects are not valid as a React child (found: object with keys {results, info})''错误:对象作为 React 子级无效(找到:带有键 {results,info} 的对象)'
【发布时间】:2020-11-02 01:48:11
【问题描述】:

当我使用 fetch 我做出反应时,我收到此错误“错误:对象作为 React 子项无效(找到:带有键 {results,info} 的对象)”

这是我的代码

    import React from "react";
import "./App.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [],
      IsLoding: false,
    };
  }

  componentDidMount() {
    fetch("https://api.randomuser.me/")
      .then(response => response.json())
      .then(data => this.setState({
        data: data,
        IsLoding: true
      }));[enter image description here][1]
  }

  render() {
    return (
      <div>
        <h1>
          Hello
          {this.state.data}
        </h1>
      </div>
    );
  }
}

export default App;

错误 [1]:https://i.stack.imgur.com/klKKP.jpg

当尝试 Consle.log(data) 时它的工作,但当尝试将数据获取到页面时不工作

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

您需要映射数据,因为您无法渲染对象。

例如,如果您只想查看性别,请尝试以下操作:

{this.state.data.results.map(item => <p>{item.gender}</p>)} 

或者你可以实现一个用户组件来呈现用户信息

{this.state.data.results.map(item => <User item={item}} />)}

映射数组时不要忘记添加 key 属性!

https://es.reactjs.org/docs/lists-and-keys.html

【讨论】:

    【解决方案2】:

    this.state.data 填充了一个对象{results, info},从那里你可以只渲染字符串或数字的属性,一些例子

    对于数组[],您需要映射它们

    {this.state.data.results.map(result => result.gender)} 
    

    本例中results是一个对象数组,map会一个一个拿到并存入变量result,这就是一个对象

    对于对象{},您需要找到要渲染的属性

    {this.state.data.info.results}
    

    现在如果你想要渲染整个对象,你需要把它转换成这样的字符串

    <pre>{JSON.stringify(this.state.data, null, 4)}</pre>
    

    【讨论】:

      猜你喜欢
      • 2021-05-19
      • 2018-01-12
      • 2020-02-27
      • 2020-11-03
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 2022-01-05
      相关资源
      最近更新 更多