【问题标题】:Objects are not valid as a React child (found: object with keys {...})对象作为 React 子对象无效(找到:带有键 {...} 的对象)
【发布时间】:2017-03-04 22:25:32
【问题描述】:

我正在尝试获取一些示例数据并在我的 react 本机应用程序中显示一些文本。这就是代码的样子(几乎直接取自教程):

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>
    );
  }
}

来自 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"}
  ]
}

我收到错误消息

如果我在函数调用之后加上toString(),[object Object] 会被打印出来,所以我猜是在返回之前将对象转换为文本的问题。谁能告诉我这是怎么做到的?

【问题讨论】:

  • JSON.stringify(...)
  • 因为您返回的是一个承诺(一个对象!)而不是字符串文字。

标签: javascript json react-native


【解决方案1】:

A.您正在返回一个从调用 getExampleData 中的 fetch 方法返回的 promise 对象,而不是您可能期望的 Star Wars

B.如果要呈现标题。最好在componentWillMount 方法中发起调用,然后在到达成功回调时使用this.setState 方法设置状态,该方法将运行render 方法。

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>
  );
}

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2020-12-28
    • 2020-05-25
    • 2021-06-28
    • 2021-05-19
    • 2018-01-12
    • 2021-05-19
    • 2020-02-27
    • 2021-09-13
    相关资源
    最近更新 更多