javascript - 如何从 fetch 中获取 JSON 数据(react-native)

标签 javascript ios json react-native fetch-api

我正在使用 React Native 为 iPhone 编写小型应用程序。我正在尝试使用 fetch 从网站获取 JSON 数据。就像在示例中一样:

   function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  }
  throw new Error(response.statusText)
}

function json(response) {
  return response.json()
}


fetch('/users', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
}).then(status)
  .then(json)
  .then(function(json) {
    console.log('request succeeded with json response', json)
  }).catch(function(error) {
    console.log('request failed', error)
  })

一切正常,但我需要稍后使用该数据。当我尝试将其分配给 json 函数中的某个变量时,出现“请求错误”,然后(正确)获取数据。获取该数据并将其保存在某个变量中以供日后使用的最佳做法是什么?

最佳答案

我是这样做的。我在控制台上显示了响应。您可以根据需要将响应数据存储在状态变量或本地存储中。

  doSignUp() {

     console.log("inside post api");
     fetch('your API URL', {
     method: 'POST',
     headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',

                },


      body: JSON.stringify({
      password: this.state.password,
      email:this.state.email,
      name: this.state.firstname,
      last_name :this.state.last_name,
      mobile:this.state.mobile,
      ssn:"2222222"

     })
      }).then((response) => response.json())
        .then((responseData) => {
                                 console.log("inside responsejson");
                                 console.log('response object:',responseData)

         }).done();
     }

关于javascript - 如何从 fetch 中获取 JSON 数据(react-native),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30061625/

相关文章:

javascript - 使用 jQuery 在另一个事件发生更改事件后弹出下拉菜单

javascript - 在javascript中平均2个十六进制颜色

javascript - 使用 javascript 检索 html 数据

ios - ipatool 无法使用 bitcode (xcode 7.1.1) 构建

ios - 只允许一个 View Controller 的所有方向

javascript - 如何从嵌套的 JSON 对象中获取已检查值的数组

javascript - 如何创建一个提取不同长度字符串的中间到末尾的函数?

iOS启动带有环境变量的应用程序

c# - Json.NET:反序列化 json 数组

javascript - 在js中将多维json转换为数组