当 Loop 在 React 中冻结页面时

While Loop freezes page in React

不确定我是否遗漏了什么,但是一个非常简单的 while 循环正在冻结页面。

选中:

Console logged inside useEffect to check if component re-rendering unusually, but that's not the case.

function IterationComponent() {

    const [c1, incrementC1] = useState(() => 0);
    const [c2, incrementC2] = useState(() => 0);

    useEffect(() => {
        console.log(1)
    }); 

    function incrementC1Fn () {
        incrementC1(prevValue => prevValue + 1)
    }

    function incrementC2Fn () {
        incrementC2(prevValue => prevValue + 1)
    }

    const isEven = () => {
        let i = 0;
        while(i < 2); i++
        return c1 % 2 === 0;
    }

    return (
        <>
            <button onClick={incrementC1Fn}>C1 - {c1}</button>
            <button onClick={incrementC2Fn}>C2 - {c2}</button>
            <span>{isEven() ? 'Even' : 'Odd'}</span>
        </>
    
    )
}

每当我在 isEven 函数中添加 while 循环时,页面就会冻结,因为我无法单击任何按钮

注意请不要问我为什么要做这样的事情或者这样做的目的是什么或者我可以用其他方式做到这一点以提高性能。 这只是为了我的理解,因为我想故意让 isEven 函数运行缓慢。这只是为了教育目的。但我认为这个简单的 while 循环不应该冻结页面,除非我在这里做错了什么。

问题出在这一行 while(i < 2); i++。您应该将其更改为 while(i < 2) i++;.

while(i < 2); 将始终计算为 true,这将无限执行并依次冻结页面。