我正在嘗試動態設定一個數組,並使用useState hook進行渲染。但似乎數組沒有設定。以下是我的程式碼:
import React, { useState, useEffect } from "react"; export default ({ item }) => { const [attachments, setAttachments] = useState([]); const setAttachmentValues = function(response){ setAttachments(response.data); } const fetchMedia = async ()=> { setAttachments([]); await apiCall().then((response) => { setAttachmentValues(response); }); } useEffect(() => { fetchMedia(); }, []); return ( <> <div className="w-full"> {(attachments.map((ele) => { <div>{ele}</div> )} </> ) }
apiCall()
將傳回一個物件陣列。
在某些情況下,以這種方式設定狀態是有效的。這裡的實際問題是什麼?
這樣你就可以渲染資料了