在开发平常的react项目的时候,我们可能会对一个数据进行数据判断,然后在进行setstate更新其他的状态。比如
const mouse = useMouse()
const [height, setheight] = useState(722)
if (mouse.clientY > 669) {
setheight(669)
} else {
setheight(722)
}
但是这样就会造成钩子无限循环调用 ,原因肯可能是因为react中的hooks不能再条件语句里面执行hooks,需要写到useEffect里面
const mouse = useMouse()
const [height, setheight] = useState(722)
useEffect(() => {
if (mouse.clientY > 669) {
setheight(669)
} else {
setheight(722)
}
}, [mouse]);
如果在useEffect里面对数据进行一个监听,然后在进行判断就会解决这个问题。