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

Mic*_*cki 10 javascript json ios 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)
  })
Run Code Online (Sandbox Code Playgroud)

一切正常,但我需要稍后使用这些数据.当我尝试将它分配给json函数中的某个变量时,我得到"请求错误",然后获取数据(正确).获取该数据并将其放入某个变量以便以后使用它的最佳做法是什么?

cod*_*z18 7

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

  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();
     }
Run Code Online (Sandbox Code Playgroud)


nic*_*sso 6

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

constructor(props) {
    super(props);
    this.state = {
       jsonData: ''
    }
}
Run Code Online (Sandbox Code Playgroud)

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

 .then((responseData) => {
    this.setState({
      jsonData: responseData
    });
  })
Run Code Online (Sandbox Code Playgroud)

  • 在fetch方法中,你通常有两个这样的域:`.then((response)=> {response.text(); console.log(response);}).then((responseText)=> {console.log (responseText);}).catch((error)=> {console.warn(error);}).done();`我想知道两者中的每一个然后返回什么,为什么这样组织?它们是如何工作的? (3认同)