如何使用Usestate处理API响应以更新状态?
我正在研究API响应。我的目的是采取此API响应以更新指定的状态。
在这里,我的功能组合中的必要代码段:
const [recordImagesPayload, setRecordImagesPayload] = useState([]);
useEffect(() => {
const headers = { 'Content-Type': 'application/json' };
// const payload = JSON.stringify({ ...createPayload(), recordImage: newImage });
request(`${url}`, { headers, method: 'GET' })
.then((response: any) => response.json())
.then(json => {
var obj = JSON.parse(json);
var res: any = [];
for (var i in obj) {
res.push(obj[i]);
}
setRecordImagesPayload(res);
console.log(res);
});
}, []);
我的控制台。没有从我的最后一行代码中显示res。我可能对响应做错了什么,但我不知道该怎么办。
请帮忙。
提前致谢。 :)
I am working on an API response. My aim is to take this API response to update a specified state.
Here the neccessary code snippet from my functional componenet:
const [recordImagesPayload, setRecordImagesPayload] = useState([]);
useEffect(() => {
const headers = { 'Content-Type': 'application/json' };
// const payload = JSON.stringify({ ...createPayload(), recordImage: newImage });
request(`${url}`, { headers, method: 'GET' })
.then((response: any) => response.json())
.then(json => {
var obj = JSON.parse(json);
var res: any = [];
for (var i in obj) {
res.push(obj[i]);
}
setRecordImagesPayload(res);
console.log(res);
});
}, []);
My console.is not showing the res from my last line of code. I am probably doing something wrong with the response but I don't know what to do.
Please help.
Thanks in advance. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设请求函数正在使用fetch函数,在这种情况下,您已经在使用响应。解析那里
尝试运行此操作。在这里,我们可以只使用“ object”。
I assume the request function is using fetch function, in that case you are already parsing the json response using response.json() call, so the resolved value in the next then is not json, so you don't have to use JSON.parse there
Try running this. Here instead of creating a new array and for loop, we can just use Object.values
谢谢@akhil。我的代码中有关打字稿的次要问题,这导致了这一问题。尚未指定结果的类型,但是除此之外,Akhil的答案非常准确。非常感谢您的快速响应和支持。
这是对我有用的最终代码:
Thanks @Akhil. I had a minor issue in my code regarding Typescript which was leading to the issue. The type of the result wasn't specified, but beside that, Akhil's answer was very accurate. Many thanks for the quick response and support.
Here is the final code which worked for me: