“ setInterval”内部的函数无法从钩子接收更新的变量

时间:2019-08-13 06:08:32

标签: reactjs setinterval react-hooks

在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);
    }
}, []);

//不带钩子;

1 个答案:

答案 0 :(得分:0)

由于computeCircle实例最初仅在useEffect挂钩中进行引用,因此它在创建此函数时从闭包中获取xCircle和mouseIn值,而setInterval则在初始调用时使用。

您需要将第二个参数传递给useEffect,以便在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]);