亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

如何修改代碼以在刷新時(shí)僅顯示 20 個(gè)隨機(jī)項(xiàng)目,不包括任何訂購的項(xiàng)目?
P粉252116587
P粉252116587 2024-03-22 13:19:54
0
1
873

我在這裡問了一個(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)目?

P粉252116587
P粉252116587

全部回覆(1)
P粉464088437

您可以使用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,但如果你只是想使用它,則不需要使用它在渲染之間保留特定值。

最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板