【问题标题】:How to get JSON data from fetch (react-native)如何从 fetch 中获取 JSON 数据(react-native)
【发布时间】:2015-07-15 16:44:55
【问题描述】:

我正在使用 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 函数中的某个变量时,我得到“请求错误”,然后(正确地)获取数据。获取该数据并将其保存在某个变量中以供以后使用的最佳做法是什么?

【问题讨论】:

    标签: javascript ios json react-native fetch-api


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你可以在组件的构造函数中创建一个变量:

      constructor(props) {
          super(props);
          this.state = {
             jsonData: ''
          }
      }
      

      然后在需要时更新此变量:

       .then((responseData) => {
          this.setState({
            jsonData: responseData
          });
        })
      

      【讨论】:

      • 在 fetch 方法中,你通常有两个这样的 then:.then((response) =&gt; { response.text(); console.log(response); }) .then((responseText) =&gt; { console.log(responseText); }) .catch((error) =&gt; { console.warn(error); }) .done(); 我想知道这两个 then 返回什么,为什么它是这样组织的?它们是如何工作的?
      • @KevinZhao : 第二个是顺序执行,第一个是从响应对象中获取文本,第二个是打印文本值。
      【解决方案3】:

      首先,如您所知,每个请求都会返回一个header和一个body

      当我们使用 fetch headers 请求的默认响应。 如果我们需要body的请求,那就够了response.json()

      return fetch(url,{
        method: 'POST',//GET and ...
        headers:{
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            elm: "elm" //is fake
        })
       })
       .then((response)=>response.json()) //   <------ this line 
       .then((response)=>{
         return response ;
       });
      

      如果您的请求的 bodyhtml dom 只需使用 response.text()

      如果你想返回你的 header 不需要做任何事情,只需添加这一行 .then((response)=&gt;response.json())

      【讨论】:

      • 嗨,如果我需要放一个令牌,我放哪里?
      【解决方案4】:

      在我的例子中,我使用了带有本地护照的sails.js,但它与任何其他node.js框架非常相似,以捕获我用于登录函数(req,res)的这些变量,其中变量存储在req中。身体。在您的情况下,req.body.name 将包含“Hubot”,req.body.login 将包含“hubot”。响应将使用 res.send 发送。查看 node.js 文档了解更多详情。

      【讨论】:

        【解决方案5】:

        我就是这样工作的

        这是按钮

        <Button onPress={this._onPressButton} accessibilityLabel="tap!!!" />
        

        这是行动

          _onPressButton() {
        
          return fetch('https://facebook.github.io/react-native/movies.json')
            .then((response) => response.json())
            .then((responseJson) => {
              console.log(responseJson.movies);
            })
            .catch((error) => {
              console.error(error);
            });
        
          }
        

        结果

        [14:30:19] Array [
        [14:30:19]   Object {
        [14:30:19]     "id": "1",
        [14:30:19]     "releaseYear": "1977",
        [14:30:19]     "title": "Star Wars",
        [14:30:19]   },
        [14:30:19]   Object {
        [14:30:19]     "id": "2",
        [14:30:19]     "releaseYear": "1985",
        [14:30:19]     "title": "Back to the Future",
        [14:30:19]   },
        [14:30:19]   Object {
        [14:30:19]     "id": "3",
        [14:30:19]     "releaseYear": "1999",
        [14:30:19]     "title": "The Matrix",
        [14:30:19]   },
        [14:30:19]   Object {
        [14:30:19]     "id": "4",
        [14:30:19]     "releaseYear": "2010",
        [14:30:19]     "title": "Inception",
        [14:30:19]   },
        [14:30:19]   Object {
        [14:30:19]     "id": "5",
        [14:30:19]     "releaseYear": "2014",
        [14:30:19]     "title": "Interstellar",
        [14:30:19]   },
        [14:30:19] ]
        [14:30:19] Array [
        [14:30:19]   Object {
        [14:30:19]     "id": "1",
        [14:30:19]     "releaseYear": "1977",
        [14:30:19]     "title": "Star Wars",
        [14:30:19]   },
        [14:30:19]   Object {
        [14:30:19]     "id": "2",
        [14:30:19]     "releaseYear": "1985",
        [14:30:19]     "title": "Back to the Future",
        [14:30:19]   },
        [14:30:19]   Object {
        [14:30:19]     "id": "3",
        [14:30:19]     "releaseYear": "1999",
        [14:30:19]     "title": "The Matrix",
        [14:30:19]   },
        [14:30:19]   Object {
        [14:30:19]     "id": "4",
        [14:30:19]     "releaseYear": "2010",
        [14:30:19]     "title": "Inception",
        [14:30:19]   },
        [14:30:19]   Object {
        [14:30:19]     "id": "5",
        [14:30:19]     "releaseYear": "2014",
        [14:30:19]     "title": "Interstellar",
        [14:30:19]   },
        [14:30:19] ]
        

        【讨论】:

        • ☝︎我需要这样的按钮对不起
        • 而且我认为没有像“localhost:3000/api/signup”那样的本地和 http 主机工作
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 2021-07-26
        • 2020-06-03
        相关资源
        最近更新 更多