Reactjs “内部功能”;“设置间隔”;不从钩子接收更新的变量
在useEffect钩子中,我设置了间隔,这是运行函数“calculateCircle”。 在那里我做了一些逻辑,包括设置状态(使用useState钩子)。 钩子中的变量会被更新,我会在页面上呈现并看到它们,但这个函数会保持对旧值的控制台登录 我将我的组件更改为基于类的组件(没有挂钩),现在一切正常。 但是我想知道使用钩子的问题是什么Reactjs “内部功能”;“设置间隔”;不从钩子接收更新的变量,reactjs,setinterval,react-hooks,Reactjs,Setinterval,React Hooks,在useEffect钩子中,我设置了间隔,这是运行函数“calculateCircle”。 在那里我做了一些逻辑,包括设置状态(使用useState钩子)。 钩子中的变量会被更新,我会在页面上呈现并看到它们,但这个函数会保持对旧值的控制台登录 我将我的组件更改为基于类的组件(没有挂钩),现在一切正常。 但是我想知道使用钩子的问题是什么 const Features = () => { const block1 = React.createRef(); const shadowText
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);
}
}, []);
//没有钩子,它就能工作 由于calculateCircle实例最初仅从useEffect钩子中引用,因此它从创建此函数时的闭包中获取xCircle和mouseIn值,对于初始调用的setInterval而言 您需要将第二个参数传递给useffect,以便在xCircle或mouseIn更改时再次创建此方法
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);
}
}, [mouseIn, xCircle]);
请勾选这个问题: