簡體   English   中英

useEffect 未在 DOM 上呈現數組

[英]useEffect is not rendering an array on DOM

我正在用虛擬數據填充一個數組,一旦完成,使用 useEffect,我試圖刪除第一個索引上的元素並在 DOM 上更新它。 該數組正在控制台上更新,但更改並未反映在 DOM 上。

import './App.css';
        import { useState,useEffect } from 'react';
        import {faker} from '@faker-js/faker'
        function App() {
        
          var catsarray = []
          const [cats, changecat] = useState(()=>{
            for (let index = 0; index < 10; index++) {
              catsarray.push(faker.animal.cetacean())
            }
        
            return catsarray
          })
        
          useEffect(()=>{
           
          },[cats])
        
          const removecat = () => {
         
            cats.shift()
            changecat(cats)
          
          }
           
         return (
           <div className="App">
              <h1> List of cats </h1>  
                    <div className='wrapper'>
                    <ul>
                    <>
                    {catsarray.length > 2 ? 
                    cats.map((title, index)=>(
                       <li key={index}> {index} : {title} </li> 
                    )) : 'Array is empty' } 
                    </>
                  
                    </ul>
                    </div>
                    <button title='button' onClick={removecat}> Click me </button> 
                   
        
            </div>
          );
        }
        
        export default App;

看看這張圖片

原因就像@Jacob Smit 說的:

React 使用引用比較來確定值是否已更改。 如果您對 state 進行變異(更改)並將其提供回 setState function 反應會看到與已經存儲的值相同的值,並認為沒有要執行的操作

因此,在突變state 時,您需要使用不同的參考

例如

// assign a new array 
let tempCats = [...cats]

// operate this new array
tempCats.shift()

// set the new array to state
changecat(tempCats)

或者喜歡@Jacob Smit 的建議

changecat(cats => cats.filter((_, i) => i !== 0))

您的問題中的一個示例,稍作修改

import React from "react"
import { useState, useEffect } from 'react';

function App() {
    var faker = ["steve", "john", "cat", "dog", "alex", "big"]

    var catsarray = []
    const [cats, changecat] = useState(() => {
        for (let index = 0; index < faker.length; index++) {
            catsarray.push(faker[index])
        }

        return catsarray
    })

    useEffect(() => {
    }, [cats])

    const removecat = () => {
        let tempCats = [...cats]
        tempCats.shift()
        console.log(tempCats)
        changecat(tempCats)

        // or @Jacob Smit's suggestion
        //changecat(cats => cats.filter((_, i) => i !== 0))
    }

    return (
        <div>
            <h1> List of cats </h1>
            <div>
                <ul>
                    <>
                        {cats.length > 2 ?
                            cats.map((title, index) => (
                                <li key={index}> {index} : {title} </li>
                            )) : 'Array is empty'}
                    </>
                </ul>
            </div>
            <button title='button' onClick={removecat}> Click me </button>
        </div>
    );
}

export default App;

代碼片段顯示

 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <div id="root"></div> <script type="text/babel"> function App() { var faker = ["steve", "john", "cat", "dog", "alex", "big"] var catsarray = [] const [cats, changecat] = React.useState(() => { for (let index = 0; index < faker.length; index++) { catsarray.push(faker[index]) } return catsarray }) React.useEffect(() => { }, [cats]) const removecat = () => { let tempCats = [...cats] tempCats.shift() console.log(tempCats) changecat(cats => cats.filter((_, i) => i.== 0)) } return ( <div> <h1> List of cats </h1> <div> <ul> {cats?length > 2. cats,map((title: index) => ( <li key={index}> {index}: {title} </li> )); 'Array is empty'} </ul> </div> <button title='button' onClick={removecat}> Click me </button> </div> ). } </script> <script type="text/babel"> ReactDOM,render( <App></App>. document;getElementById("root")); </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM