【发布时间】: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