【问题标题】:Infinity loop when using useEffect while try to update children component尝试更新子组件时使用useEffect时出现无限循环
【发布时间】:2020-06-25 05:20:00
【问题描述】:

当父组件通过道具将更改传递给子组件时,我正在尝试更新组件,因此我创建了一个这样的测试程序

父组件

   function Parent(props){
     const [newCount, setNewCount] = useState(0)
     const handleClick = (event)=>{
        event.preventDefault()
        setNewCount(count+1)
     }
     return <div>
                 <button className='btn btn-primary' type='submit' onClick={handleClick}>parent</button>
                 <Test newCount = {count}/>
            </div>
}

儿童组件

function Test(props){
    const [count, setCount] = useState(0)
    const {newCount} = props
    useEffect(()=>{
        setCount(count + 1) ### marked line
    },[newCount, count])
    return <button type='submit'>{count}</button>
}

每当点击父级按钮时,子级将根据从其父级传递的“newCount”值重新渲染。我可以理解标有“###”的行会导致无限循环,但让我感到困惑的是,如果我将setCount(count+1) 替换为setCount(newCount+1),那么我将不再获得无限循环。有人可以帮我解释一下原因吗?提前谢谢你

【问题讨论】:

    标签: reactjs react-hooks infinite-loop use-effect


    【解决方案1】:

    您已将 count 作为依赖项添加到 useEffect 中,它本身会更新计数,因此 useEffect 会在循环中触发

    useEffect(()=>{
        setCount(count + 1) ### marked line
    },[newCount, count]); // problem due to use of count here
    

    当您更改为 setCount(newCount + 1) 时,您将从 useEffect 中删除依赖项计数,因此它不再导致无限循环

    既然你想根据父母更新子状态,你必须实际使用

    useEffect(()=>{
        setCount(newCount) ### marked line
    },[newCount]);
    

    但是,您可以直接使用 props 中的计数值,并通过从 parent 作为 props 传递更新器函数来更新它,而无需复制到本地状态

    P.S. 可能只是帖子中的一个错字,但在父级中您需要在更新状态时使用newCount 而不是count,因为在父级中未定义计数

    const handleClick = (event)=>{
        event.preventDefault()
        setNewCount(newCount+1)
     }
    

    【讨论】:

      【解决方案2】:

      在你的子组件中从 useEffect 中删除计数,我希望它会有所帮助

      function Test(props){
        const [count, setCount] = useState(0)
        const {newCount} = props
        useEffect(()=>{
          setCount(count + 1) ### marked line
        },[newCount])
        return <button type='submit'>{count}</button>
      }
      

      【讨论】:

        猜你喜欢
        • 2020-07-01
        • 1970-01-01
        • 2023-03-22
        • 2020-01-31
        • 2012-10-27
        • 2021-07-25
        • 1970-01-01
        • 2012-07-06
        • 1970-01-01
        相关资源
        最近更新 更多