[英]How to use slice() in react.js when fetching with react UseEffect
我想弄清楚如何使用“const currentPosts”。 我正在通過所有獲取的對象 (pakketjes) 進行映射,並且正在展示它們中的每一個。 但我只想顯示 const currentPosts 中聲明的對象數量。 這是代碼
export default function HomePagina() {
const paperStyle = { padding: '20px 20px', width: 600, margin: "20px auto", backgroundColor: "#F2D2BD", borderRadius: "35px" };
const [pakketjes, setPakketjes] = React.useState([]);
const [currentPage, setCurrentPage] = React.useState(2);
const [postsPerPage, setpostsPerPage] = React.useState(2)
const lastPostIndex = currentPage * postsPerPage;
const firstPostIndex = lastPostIndex - postsPerPage;
const currentPosts = pakketjes.slice(firstPostIndex, lastPostIndex)
//useffect = voor bij pagina starten om info te loaden, in dit geval alle pakketjes tonen bij opstart
React.useEffect(() => {
fetch("http://localhost:8080/pakketje/getAll")
.then(res => res.json())
.then((result) => {
setPakketjes(result);
}
)
}, []);
return (
<>
<Appbar />
<br />
<Container>
<div>
<img src={AllePakketjes} width="410" height="350" alt="" style={{ marginLeft: "365px" }} />
</div>
<h1 style={{ textAlign: "center", color: "white" }}>Alle pakketjes</h1>
<Paper elevation={3} style={paperStyle}>
{pakketjes.map(pakketje => (
<Paper elevation={6} style={{ margin: "10px", padding: "15px", textAlign: "left", backgroundColor: "white", borderRadius: "25px" }} key={pakketje.id}>
<b>Pakketje    </b>
<br /><br />
<b>ID:</b>{pakketje.id}
<br /><br />
<b>Status: </b>{pakketje.status}
<br />
<b>Code:</b>{pakketje.code}
<br /><br />
<Button variant="contained" style={{ backgroundColor: "#AE0000" }} color="secondary" onClick={(e) => deletePakketje(pakketje.id, e)}>
Delete <DeleteIcon fontSize="small" />
</Button>  
<Link to={`/pakketjeUpdaten/${pakketje.id}`}>
<Button variant="contained" style={{ backgroundColor: "Navy" }} color="secondary">
Update <ReplayIcon fontSize="small" />
</Button>
</Link>  
<Button variant="contained" style={{ backgroundColor: "black" }} color="secondary" onClick={(e) => statusOnderweg(pakketje.id, e)}>
Verzenden <LocalShippingIcon fontSize="small" />
</Button>
<br />
<br />
</Paper>
))
}
</Paper>
</Container>
</>
);
}
看起來您可以將pakketjes.map
替換為currentPosts.map
。
這將遍歷currentPosts
指定的pakketjes
子集而不是整個數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.