react-native - 在另一个 fetch 中使用从 promise 返回的数据不起作用
问题描述
我有一个handleSubmit 函数,我添加了两个post 请求。
但是,其中一个发布请求依赖于从第一个发布请求返回的数据。我试图通过将其设置为 var 来访问这些数据,但在第二次提取中似乎无法访问它。不确定我的语法是否错误..有什么想法吗?
我相信这应该可行,但我不确定我哪里出错了。谢谢!
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
var dataId = data.id;
})
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: dataId,
user_id: this.props.users.id
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}
解决方案
有2个问题:
- 你
return
一些代码,然后尝试运行其他东西。您的this.props.navigation.goBack()
语句将永远无法到达,因为函数在到达return
. 不过,这不是您的主要问题。 fetch
是异步的。这意味着函数 handleSubmit 将读取前两个语句(“获取资源”和“返回获取用户资源”),然后当每个获取完成时,它们将运行它们的.then()
函数。
这意味着您dataId
将未定义,您需要等待第一次提取完成并执行第二次提取。
handleSubmit = () => {
fetch('http://localhost:3000/resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
name: this.state.name,
description: this.state.description,
link: this.state.link,
topic_id: this.state.topic_id
})
})
.then(res => res.json())
.then(data => {
this.props.addResource(data)
return fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: data.id,
user_id: this.props.users.id
})
})
})
.then(res => res.json())
.then(data => {
this.props.addUserResource(data)
})
this.props.navigation.goBack()
}
推荐阅读
- python - 直接在pyuic5生成的py文件上写函数是个好主意吗?
- python - 为什么我在 pandas 中使用过滤器时会出现此错误:TypeError: 'int' object is not iterable
- javascript - 动画宽度的更好解决方案
- css - 修复第一个 Div 并仅调整第二个 Div 的大小 - 第 2 列下的第 3 列
- angular - 从 angular-5 迁移到 angular-9 后,Angular 智能表无法正常工作
- bash - 如何正确阅读 Shell 语法?
- ios - 我不希望代码在键盘上的删除按钮时工作
- c++ - 自定义引用包装器的 const 正确性
- monaco-editor - 如何在 monaco-editor 中手动创建文本模型实例?
- firebase - 如何以 excel 或 CSV 格式查询 Firebase Firestore(非实时数据库)集合和检索数据