我正在尝试动态设置一个数组,并使用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()
将返回一个对象数组。
在某些情况下,以这种方式设置状态是有效的。这里的实际问题是什么?
P粉8685860322023-09-09 10:58:22
这样你就可以渲染数据了
import React, { useState, useEffect } from 'react'; export default ({ item }) => { const [attachments, setAttachments] = useState([]); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/users') .then((response) => response.json()) .then((response) => { setAttachments(response); console.log(response); }); }, []); return ( <> <div> {attachments.map(item => <div key={item.username}> {item.username} </div> )} </div> </> ); };