簡體   English   中英

如何使用 useState 處理 API 響應以更新 state?

[英]How do I handle an API response with useState to update a state?

我正在處理 API 響應。 我的目標是利用這個 API 響應來更新指定的 state。

這是我的功能性 compon.net 中的必要代碼片段:

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);
      });
  }, []);

我的控制台沒有顯示我最后一行代碼的資源。 我可能在響應中做錯了什么,但我不知道該怎么做。

請幫忙。

提前致謝。 :)

我假設請求 function 使用的是 fetch function,在這種情況下,您已經使用 response.json() 調用解析了 json 響應,因此接下來解析的值不是 json,因此您不必使用 JSON。在那里解析

嘗試運行它。 在這里,我們可以使用 Object.values 而不是創建新數組和 for 循環

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);
          });
      }, []);

謝謝@Akhil。 我的代碼中有一個關於 Typescript 的小問題導致了這個問題。 沒有指定結果的類型,但除此之外,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);
          });
      }, []);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM