.map 只返回数组 React 的最后一个元素

.map is returning only the last element of array React

我正在使用 Cloud Firestore 创建一个博客类型的应用程序,作为一个学习一些东西的项目。但是我遇到了一个问题,我的状态数组 'blogs' 的最后一个元素在 .map 方法中被返回。

感谢任何帮助,谢谢!

const [blogs, setBlog] = useState([]);
const fetchBlogs = async () => {
    const response = await getDocs(collection(db, "blog posts"));
    let postArray = [];
    response.docs.forEach((blogpost) => {
        postArray.push(blogpost.data());
    });
    console.log(postArray)
    postArray.forEach(post => {
        setBlog([...blogs, post]);
    });
}
useEffect(() => {
    fetchBlogs();
}, []);

return (
    <ul className="posts-container">
       { blogs.map((blog) => { 
           console.log(blog); //this outputs each of the individual posts, but only the last is displayed as an <li>
           return ( <li key={blog.title}>{blog.title}</li> )
        })}
    </ul>
)

而不是这个:

postArray.forEach(post => {
  setBlog([...blogs, post]);
});

尝试这样做:

setBlog(postArray);

我不确定到底发生了什么,但这似乎是您代码中最可疑的部分。

你覆盖博客post两次,试试这个

const fetchBlogs = async () => {
    const response = await getDocs(collection(db, "blog posts"));
    setBlog([...blogs, ...response.docs.map(blogpost => blogpost.data())])
}

useEffect(() => fetchBlogs(), []);

您可能希望在不执行 forEach()

的情况下将响应置于您的状态
setBlog(postArray);

甚至(取决于数据结构)

const [blogs, setBlog] = useState([]);

const fetchBlogs = async () => {
    const response = await getDocs(collection(db, "blog posts"));
    setBlog(response.data); // set to whatever you need
}

useEffect(() => {
    fetchBlogs();
}, []);

return (
    <ul className="posts-container">
       { blogs.map((blog) => { 
            return <li>( <li key={blog.title}>{blog.title}</li> )
          }
       )}
    </ul>
);