简体   繁体   中英

'Error: Objects are not valid as a React child (found: object with keys {results, info})'

when i use fetch i react i got this error 'Error: Objects are not valid as a React child (found: object with keys {results, info})'

this is my code

    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;

the error [1]: https://i.stack.imgur.com/klKKP.jpg

when try Consle.log(data) its working but when try to get the data to page not working

You need to map the data, because you can't render an object.

For example if you wanna see only the genders try this:

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

Or you could implement a user component that render the user information

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

Dont forget to add the key prop when mapping an array!

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

this.state.data gets populated with an object {results, info} , from there you can render only the properties that are strings or numbers, some examples

For arrays [] , you will need to map them

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

in this case, results is an array of objects, map will get one by one and store it in the variable result , and this will be an object

For objects {} , you will need to find the property you want to render

{this.state.data.info.results}

Now if what you want is to render the whole object as it is, you need to convert it to a string like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM