首页 > 解决方案 > React Native 中的“双重获取”调用问题

问题描述

我在 React Native 函数中使用“嵌套”Fetch 调用时遇到问题。似乎第一个 Fetch 可以正常工作,但是第二个会引发错误。这是代码:

     //****CALL TWO FETCH REQUESTS...
const data = { passkey: '12345', callup: 'name' };
const secondary = { passkey: '12345', callup: 'name' };

 fetch('https://myremoteserveraddress', {
   method: 'POST', 
   headers: {
     'Content-Type': 'application/json',
   },
   body: JSON.stringify(data),
 })
 .then(function(response) {

   if (response.ok) {
    return response.json();
   } else {
    return Promise.reject(response);
   }

 })
 .then(data => {

  // Store the post data to a variable
  _post = data;
  console.log('Success on FIRST FETCH:', data);
  console.log('answer is:', data.answer);
  console.log('answer is:', _post.answer);

  // Fetch another API
    fetch('https://myremoteserveraddress', {
     method: 'POST',
     headers: {
       'Content-Type': 'application/json'
     },
     body: JSON.stringify(secondary),
    })

 })
 .then(function (response) {

  if (response.ok) {
    return response.json();
  } else {
    return Promise.reject(response);
  }

 })
 .then(function (userData) {

 console.log('Returned from BOTH fetch calls');  //does not write to console
 console.log(_post, userData);  //does not write to console
 this.vb.start();
 })
 .catch((error) => {
   console.error('Error in onPressPublishBtn:', error);
 });
 //****

尽管与似乎成功工作的第一个 Fetch 调用相同,但似乎第二个 Fetch 调用返回“未定义”。返回的错误是“TypeError: undefined is not an object (evalating 'response.ok')”。如果有人可以就问题所在提出建议,我将不胜感激。先感谢您。

标签: javascriptreact-nativetypeerrorfetch-api

解决方案


您应该从第二个then(...)块返回一个 Promise,以便将响应传递给第三个then(...)块。您可能想尝试这样的事情:

// Fetch another API
return fetch('https://myremoteserveraddress', {
 method: 'POST',
 headers: {
   'Content-Type': 'application/json'
 },
 body: JSON.stringify(secondary),
})

推荐阅读