简体   繁体   中英

Objects are not valid as a React child (found: object with keys {…})

I'm trying to fetch some example data and display some text in my react native app. This is how the code looks (pretty much taken straight from the tutorial):

function getExampleData() {
  return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies[0].title;
    })
    .catch((error) => {
      console.log(error);
      return 'Error!';
    });
}

class CenterView extends React.Component {
  render() {
    return (
      <Text>{getExampleData()}</Text>
    );
  }
}

The response body from the url:

{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}

I'm getting the error message

在此处输入图片说明

If I put toString() after the function call, [object Object] is printed out, so I guess it's a matter of turning the object into text before returning. Can anyone tell me how this is done?

A. You are returning a promise object returned from the call to fetch method in getExampleData and not Star Wars as you might be expecting.

B. If you want to render the title(s). It is better that you initiate the call in componentWillMount method and then upon arrival in the success callback set the state using this.setState method which would run the render method.

getExampleData() {
  return fetch('https://facebook.github.io/react-native/movies.json')
   .then((response) => response.json())
    .then((responseJson) => {
     return responseJson.movies[0].title;
   })
   .catch((error) => {
     console.log(error);
     return 'Error!';
   });
}
componentWillMount() {
  getExampleData().then(function (title) {
    this.setState({
      title
    })
  })
}

render() {
  return (
    <Text>{this.state.title}</Text>
  );
}

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