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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30061625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:36:02  来源:igfitidea点击:

How to get JSON data from fetch (react-native)

javascriptiosjsonreact-nativefetch-api

提问by Micha? Zubrzycki

I'm writing small app for iPhone using react native. I'm trying to fetch JSON data from a website using fetch. Like in the example:

我正在使用 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)
  })

Everything works fine but I need to use that data later. When I try to assign it to some variable in json function, I get "Request error" and after that get the data (correctly). What's the best practise to get that data and have it in some variable to use it later?

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

回答by coderzzz18

I did it like this. I displayed the response on console. You can store the response data in your state variable or in local storage as you want.

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

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

回答by Niccolò Passolunghi

You can create a variable in the component's constructor:

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

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

Then you update this variable when you needed:

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

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

回答by Bashirpour

My dear friend, this is very simple

亲爱的朋友,这很简单

Firstly, as you know, each request returns a headerand a body

首先,如您所知,每个请求都会返回一个标头和一个正文

When we use fetcha default response that is headersrequest. If we need to bodyof request, that's enough response.json()

当我们使用fetch 时,默认响应是headers请求。如果我们需要请求的主体,这就足够了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 ;
 });

And if the bodyof your request is html domJust use this response.text()

如果你的请求正文html dom就用这个response.text()

And if you want to return your headerno need to do anything, Just add this line .then((response)=>response.json())

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

回答by Ryosuke Hujisawa

Me works like this

我是这样工作的

This is button

这是按钮

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

This is action

这是行动

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

  }

result

结果

[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] ]

回答by Mounir Dhahri

In my case, i used a sails.js with passport local but it's very similar to any other node.js framework, to catch these variables I used for signin a function(req,res) where variables where stored in req.body. In your case req.body.name will contain 'Hubot' and req.body.login will contain 'hubot'.Response will be sent using res.send. check the node.js documentation for more details.

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