react-native - 何时返回 fetch() 以及何时仅使用 fetch() 请求?
问题描述
我开始使用本机反应,我一直想知道的一件事是,有时我看到 fetch 是这样使用的:
createTodo(){
fetch('http://192.168.1.34:3000/createTodo', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: this.state.noteText,
}),
}).then((response) => response.json())
.then((responseJson) => {
var d = new Date();
this.state.noteArray.push({
'date':d.getFullYear()+
"/"+(d.getMonth()+1) +
"/"+ d.getDate(),
'note': responseJson.data.content
});
this.setState({ noteArray: this.state.noteArray });
this.setState({noteText:''});
console.log(responseJson);
}).catch((error) => {
console.error(error);
console.log('Shit! Error occured');
});
}
这项工作很好。
有时是:
return fetch(...)...
我有点困惑。
解决方案
fetch
是返回另一个 Promise 的 Promise。解析结果传递给下一个.then
输入参数。因此,在您的示例代码中,您可以处理response
由fetch
函数传递的值。
fetch
当客户createTodo
想要使用 的“结果”时,您可以返回您的函数createTodo
。“结果”是另一个 Promise,其输入参数来自createTodo
的返回值
Demo只是为了展示Promise的返回值是另一个Promise。我希望你能得到提示。
推荐阅读
- process - 在 Python 3.8 中获取进程的写入/读取字节和 cpu 使用率的问题
- sql - 在 ON CONFLICT UPDATE 的 INSERT 值列表中使用额外的列
- php - 购物车更新后 WooCommerce 购物车数量不会改变
- python - 用另一个 2d 列表过滤 2d 列表
- php - 如何使按钮颜色与我的代码匹配
- azure-pipelines - Azure 管道触发不包含相同管道的分支
- java - 我重新安装 android studio 后 Gradle 同步失败
- javascript - 不确定如何在本机反应中配置此工具提示功能
- azure - 如何将 API 数据加载到 Azure Synapse?
- ruby-on-rails - Ubuntu:无法安装 sqlite3 - 无法构建 gem 本机扩展