【发布时间】:2019-01-21 17:07:16
【问题描述】:
我有两个请求,一个 GET 和一个 POST 请求,我正在获取 GET 请求并在数组内部设置响应状态,我想将此数组传递给 POST 请求正文,然后我正在获取 POST 请求所以我可以打电话,问题是它没有在 GET 调用中设置状态,它总是返回未定义,我不知道为什么,这里是代码:
我的构造函数:
constructor(props){
super(props);
this.state = {
info: [],
}
}
功能:
myFunction = async () => {
fetch("https://myapp.com/info", {
method: "GET",
headers: {
"Content-Type": "application/json",
"x-auth-token": token
}
})
.then(res => res.json())
.then(response => {
this.setState({ info: response });
fetch("https://myapp.com/submit_info", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-auth-token": token
},
body: JSON.stringify({
infoID: this.state.info.id
})
})
.then(res => res.json())
.then(result => {
console.log(result);
});
})
.catch(error => console.log(error));
};
【问题讨论】:
-
React 的
setState调用也是异步的。您应该只使用来自GET请求的数组结果作为POST请求的输入。我认为没有必要在下一个请求之前先将其保存到状态。 -
查看 React 中 setState 的文档。它是异步的,因此需要像
this.setState({ info: response}, () => { ...second fetch here })这样的回调
标签: javascript api react-native fetch