简体   繁体   English

useEffect 未在 DOM 上呈现数组

[英]useEffect is not rendering an array on DOM

I am populating an array with dummy data and once it is done, using useEffect, i'm trying to delete the the element on first index and update it on the DOM.我正在用虚拟数据填充一个数组,一旦完成,使用 useEffect,我试图删除第一个索引上的元素并在 DOM 上更新它。 The array is being updated on console but the changes doesn't reflect on 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;

看看这张图片

The reason is like @Jacob Smit said:原因就像@Jacob Smit 说的:

React uses referential comparisons to determine whether or not a value has changed. React 使用引用比较来确定值是否已更改。 If you mutate (change) the state and provide it back to the setState function react sees the same value as it already has stored and thinks there is no operation to be carried out如果您对 state 进行变异(更改)并将其提供回 setState function 反应会看到与已经存储的值相同的值,并认为没有要执行的操作

So you need to use a different refernece when mutating a state因此,在突变state 时,您需要使用不同的参考

for example例如

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

// operate this new array
tempCats.shift()

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

Or like @Jacob Smit's suggestion或者喜欢@Jacob Smit 的建议

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

a example from your question with a little modify您的问题中的一个示例,稍作修改

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;

a code snippet display代码片段显示

 <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