Rumah  >  Soal Jawab  >  teks badan

Mengapa useEffect mengabaikan elemen terakhir tatasusunan?

<p>Saya sedang belajar React, terutamanya belajar useEffect. </p> <p>Apa yang saya tidak faham ialah mengapa useEffect melangkau elemen terakhir tatasusunan. </p> <p>Bolehkah seseorang menerangkan sebab dan cara untuk membetulkannya? </p> <pre class="brush:php;toolbar:false;">biarkan pengguna = ['Oliver', 'Thomas', 'George', 'William'] eksport fungsi lalai App() { const [indeks, setIndex] = useState(0); console.log('RENDER'); useEffect(() => { if (index === users.length - 1) { kembali } setTimeout(() => setIndex(index => indeks + 1), 2000) console.log('Hello ' + pengguna[indeks]); console.log('Kesan Sampingan BERJALAN!'); }, [pengguna[indeks]]) }</pre> <p><br /></p>
P粉814160988P粉814160988404 hari yang lalu355

membalas semua(1)saya akan balas

  • P粉553428780

    P粉5534287802023-08-15 00:58:02

    Nilai useEffect不会运行,因为users[index] anda adalah sama

    Tukar kepada index

    let users = ['Oliver', 'Thomas', 'George', 'William']
    export default function App() {
      const [index, setIndex] = useState(0);
      console.log('RENDER');
      useEffect(() => {
        if (index === users.length - 1) {
          return
        }
        setTimeout(() => setIndex(index => index + 1), 2000)
        console.log('Hello ' + users[index]);
        console.log('Side Effect RUNS!');
      }, [index]) // 更改为 `[index]`
    
    }

    balas
    0
  • Batalbalas