如何使用Usestate处理API响应以更新状态?

发布于 2025-01-21 16:51:21 字数 752 浏览 2 评论 0原文

我正在研究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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幸福还没到 2025-01-28 16:51:21

我假设请求函数正在使用fetch函数,在这种情况下,您已经在使用响应。解析那里

尝试运行此操作。在这里,我们可以只使用“ object”。

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(result => {
            const res = Object.values(result);
            setRecordImagesPayload(res);
            console.log(res);
          });
      }, []);

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

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(result => {
            const res = Object.values(result);
            setRecordImagesPayload(res);
            console.log(res);
          });
      }, []);
近箐 2025-01-28 16:51:21

谢谢@akhil。我的代码中有关打字稿的次要问题,这导致了这一问题。尚未指定结果的类型,但是除此之外,Akhil的答案非常准确。非常感谢您的快速响应和支持。

这是对我有用的最终代码:

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(result: any => {
            const res = Object.values(result);
            setRecordImagesPayload(res);
            console.log(res);
          });
      }, []);

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:

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(result: any => {
            const res = Object.values(result);
            setRecordImagesPayload(res);
            console.log(res);
          });
      }, []);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文