英文:
Expected infinite re-rendering but didn't happen
问题
import React, { useState, useEffect } from "react";
export default function Example() {
const [count, setCount] = useState(0);
const [tmp, setTmp] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
setTmp(count);
console.log(tmp);
});
return (
<div>
<p>
You clicked {count} times and temp is {tmp}
</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
英文:
import React, { useState, useEffect } from "react";
export default function Example() {
const [count, setCount] = useState(0);
const [tmp, setTmp] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
setTmp(count);
console.log(tmp);
});
return (
<div>
<p>
You clicked {count} times and temp is {tmp}
</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
After reading this I expected this to cause infinite re-render because a state tmp
is getting changed inside the useEffect but it didn't, can someone please help what might be the cause?
答案1
得分: 3
React的setter在值没有改变的情况下会忽略设置。重复调用setTmp(0)
不会触发新的渲染。将其更改为setTmp(n => n+1)
,你将获得你所期望的无限循环。
英文:
React setters ignore the set if the value didn't change. Repeatedly calling setTmp(0)
will not trigger new renders. Change it to setTmp(n => n+1)
and you will get the infinite loop you're looking for.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论