我在這裡問了一個(gè)關(guān)於如何從該 JSON 中獲取 20 個(gè)隨機(jī)項(xiàng)目的問題,我使用瞭如下答案之一:
const a = Myjson; useEffect(() => { for (let i = a.length; i-- > 0; ) { const j = Math.floor(Math.random() * i); // 0 ≤ j ≤ i [a[i], a[j]] = [a[j], a[i]]; } }, []); {a .slice(0, 20) .map((item) => ( <Link href={item.ud} key={item.id} > {item.test} </Link> ))}
有一個(gè)問題,當(dāng)我刷新時(shí),我看到該JSON 的有序20 個(gè)項(xiàng)目,然後突然變?yōu)殡S機(jī)20 個(gè)項(xiàng)目;如何修復(fù)程式碼,以便當(dāng)我刷新時(shí)只能看到隨機(jī)的20 個(gè)項(xiàng)目,而看不到那些訂購的項(xiàng)目?
您可以使用useState
來提供在第一次渲染時(shí)產(chǎn)生的一致(隨機(jī))排序,而不是使用useEffect
在第一次渲染後更新排序:
const [a] = useState(() => { // Same code as in your useEffect, but with `a` renamed for clarity let b = [...Myjson]; // take a copy of the array for (let i = b.length; i-- > 0; ) { const j = Math.floor(Math.random() * i); // 0 ≤ j ≤ i [b[i], b[j]] = [b[j], b[i]]; } return b; // Return value is used as the state value }); // ... rendering code as before
useState
將在元件第一次渲染時(shí)執(zhí)行初始化程式碼。雖然 useState
也傳回一個(gè)setter,但如果你只是想使用它,則不需要使用它在渲染之間保留特定值。