javascript - 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')”。如果有人可以就问题所在提出建议,我将不胜感激。先感谢您。
解决方案
您应该从第二个then(...)块返回一个 Promise,以便将响应传递给第三个then(...)块。您可能想尝试这样的事情:
// Fetch another API
return fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})
推荐阅读
- anti-patterns - 用于渲染整个页面的 OpenComponents
- android - 如何在自定义视图中添加可绘制资源
- python - Python Dash (Plotly): TypeError: unhashable type: 'Div'
- git - 当我推送到 git 时,我收到组件名称太长的错误
- html - 浏览器从 srcset 中为视口选择错误的图像
- vba - 如何将动态值历史记录保存到带有时间戳 VBA/Excel 的行中
- javascript - 我在使用 Internet Explorer 11 的 Fetch API 时遇到问题
- android - Message Dark模式的背景颜色代码是什么
- php - Yii2 kartik\daterange\DateRangePicker not working in On Focus
- c++ - int() 导致参数被覆盖