尝试更新子组件时使用useEffect时的无限循环

时间:2020-06-25 05:20:00

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

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

父项

   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),那么我就不会再出现无限循环了。有人可以帮我解释原因吗?预先谢谢你

2 个答案:

答案 0 :(得分:0)

您已将count作为useEffect的依赖项添加,它本身会更新count,因此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来更新计数值,而无需复制到本地状态

PS 可能只是帖子中的错字,但在父级中,由于未在父级中定义计数,因此在更新状态时,您需要使用newCount而不是count / p>

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

答案 1 :(得分:0)

在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>
}