javascript - 如何在 React Native 中访问 json 对象的字符串

标签 javascript json reactjs react-native

我正在尝试制作一个应用程序,使用 wiki quote api 显示名人(例如 Bob Dylan)的名言。

请求 url 如下所示:

https://en.wikiquote.org/w/api.php?format=json&action=parse&page=Bob_Dylan&prop=text

我有 React Native 请求:

componentWillMount() {
Api().then((response) => {
  this.setState({
    quote:response.parse.text

  })

});
}

但是,当我尝试显示引号时,它以对象的形式出现并在 View 中获取 [object object]。在我收到的控制台中:

Possible Unhandled Promise Rejection (id: 0): Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Text. Invariant Violation: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Text.

当我尝试 response.parse.text.* 时,我收到一个 token 错误。有什么建议可以解决这个问题吗?

最佳答案

您必须通过调用其 json() 方法显式地将 response 转换为 Object ,例如:

 var url = 'https://en.wikiquote.org/w/api.php?format=json&action=parse&page=Bob_Dylan&prop=text';

 fetch(url)
   .then((response) => response.json())
   .catch((error) => console.warn("fetch error:", error))
   .then((response) => console.log(response.parse))

工作示例:https://rnplay.org/apps/EqyMdA

关于javascript - 如何在 React Native 中访问 json 对象的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38132330/

相关文章:

javascript - Axios - 未捕获( promise )错误 : Request failed with status code 500

javascript - 使用 jquery 删除外部元素

javascript - 在单个 div 单击上绑定(bind)输入字段

javascript - 如何在 Joi 中的值上验证具有两个最大条件的对象?

javascript - Express json() 创建奇怪的 JSON(键与值合并)

python - 如何配置 Django Rest Framework + React

android - 如何删除原生选项卡的边框

javascript - 在 Javascript 中的对象递归循环的输出中保留顺序

java - Gson反序列化跳过一引号

javascript - 如何正确地从 ReactJS + Redux 应用程序进行 REST 调用?