【发布时间】:2021-11-04 04:41:41
【问题描述】:
第一次加载页面时,我正在努力获取“lovedList”值。重新渲染时,列表会正确更新。我怎样才能让它等待列表值从 useEffect 呈现第一个对象?
import { Post, PostProps } from "./Post";
import { useEffect, useState, useCallback } from "react";
import { api } from "../services/api";
import { useSession } from "next-auth/client";
export function PostList() {
const [session, status] = useSession();
const [loading, setLoading] = useState(true);
const [data, setData] = useState<PostProps[]>([])
const [skip, setSkip] = useState(0)
const take = 3
let list = []
async function getUserPurchases() {
if (session) {
const response = await api.get(`/purchases/${session?.id}`)
response.data.map(purchase => {
list.push(purchase.postId)
})
}
return list
}
async function handleLoadMore() {
setLoading(true)
const lovedList = await getUserPurchases();
setSkip(skip + take)
const newPosts = await api.get(`/post?take=${take}&skip=${skip}`)
const formattedData = newPosts.data.map(post => {
console.log(lovedList)
return {
id: post.id,
image: post.image,
institution: post.institution,
title: post.title,
description: post.description,
createdAt: new Date(post.createdAt).toLocaleDateString('pt-BR', {
day: '2-digit',
month: 'long',
year: 'numeric'
}),
loved: lovedList.includes(post.id),
author: {
image: post.author.image,
name: post.author.name,
id: post.author.id
}
}
})
setData([...data, ...formattedData])
setLoading(false)
}
useEffect(() => {
handleLoadMore()
}, [])
if (loading) {
return <h1>Carregando</h1>
}
return (
<main className="flex flex-col md:max-w-3xl xl:max-w-6xl mx-auto text-gray-200 text-6xl ">
{data && data.map(post => (
<Post
key={post.id}
image={post.image}
institution={post.institution}
title={post.title}
description={post.description}
createdAt={post.createdAt}
loved={post.loved}
author={post.author}
id={post.id}
/>
))}
<button
type="button"
className="px-4 py-3 bg-blue-400 rounded-full outline-none flex items-center
justify-center text-sm my-16 mx-auto w-4/12 hover:bg-blue-500
transition-colors duration-200 ease-out"
onClick={handleLoadMore}
>
Carregar Mais
</button>
</main>
);
}
当我加载页面时,console.log 返回空数组。如果接下来的几个项目加载,他们 console.log 属性列表。第一次访问该页面时如何使其正确加载?
谢谢!
【问题讨论】: