【发布时间】:2019-12-19 16:05:42
【问题描述】:
在 useEffect-hook 中我设置了间隔,它正在运行函数“calculateCircle”。 在那里我做了一些逻辑,包括设置状态(使用useState-Hook)。 来自钩子的变量已更新,我在页面上渲染并查看它们,但此函数不断合并旧值。
我将组件更改为基于类的组件(没有挂钩),现在一切正常。 但我想知道使用钩子的问题是什么。
const Features = () => {
const block1 = React.createRef();
const shadowText = React.createRef();
const [ mouseIn, setMouseIn ] = useState(false);
const [ xCircle, setXCircle] = useState(-50);
const calculateCircle = () => {
console.log('mouseIn :', mouseIn); //never changes, but in page - yes
if (!mouseIn) { //never skips this loop
console.log('begin', xCircle);//always the same
let r = 50;
let yCircle = Math.sqrt(r*r - xCircle*xCircle);
if (shadowText.current) draw(xCircle, yCircle);
setXCircle(prev => {
console.log('xCircle:', prev);
return prev > 50 ? -50 : prev + 1
});
console.log('end', xCircle, yCircle);
}
} //on page I see that xCircle changes correctly
useEffect(() => {
const cycle = setInterval(() => calculateCircle(), 1000);
return () => {
clearInterval(cycle);
}
}, []);
//不用钩子就可以了;
【问题讨论】:
标签: reactjs setinterval react-hooks