简体   繁体   English

useEffect 在初始渲染后不触发

[英]useEffect does not trigger after initial render

I have an array of 16 objects and I use "number" prop to cut unwanted elements.我有一个包含 16 个对象的数组,我使用“数字”道具来剪切不需要的元素。 So if I want an array of 8 elements I would type:所以如果我想要一个包含 8 个元素的数组,我会输入:

<Images number="8"/>

However my useEffect does not run after initial render, but only after I make a change in the array later on, this returns all 16 elements, if I make a typo, wait for a bug screen to render and fix a typo, my browser shows 8 elements as it should.但是我的 useEffect 在初始渲染后不会运行,但只有在我稍后对数组进行更改后,才会返回所有 16 个元素,如果我输入错误,请等待错误屏幕渲染并修复错误,我的浏览器会显示8 元素,因为它应该。 This is the rest of my code:这是我的其余代码:

const Images = (props) => {
    const [deck, setDeck] = useState(data);
    // data.length is equal 16

    const sliceDeck = () => {
        data.splice(parseInt(props.number, 10), data.length)
    }
    
    useEffect(()=>{
        sliceDeck()
        setDeck(data)
    }, [])

    return (
        <>
        <div className="img-container">
           {deck.map(object => <div className="img-on" key={object.id}><img src={object.src} alt=""/></div>)}
        </div>

        </>
    );
  }
  
  export default Images;

You need to add props.number to the dependency array to make sure it runs every time there is an update to it您需要将props.number添加到依赖项数组以确保它在每次有更新时运行

 const Images = (props) => { const [deck, setDeck] = useState(data); useEffect(()=>{ if(!isNaN(props?.number)){ const temp = data.splice(parseInt(props?.number, 10), data.length) setDeck(temp) } }, [props?.number]) return ( <> <div className="img-container"> {deck.map(object => <div className="img-on" key={object.id}> <img src={object.src} alt=""/> </div>)} </div> </> ); } export default Images;

emphasized text强调文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM