为什么只更新计数而不更新用户名
import React, { useState } from "react";
import ReactDOM from "react-dom";
function ReposGrid({ id }) {
const [count, setCount] = useState(0);
var username = "Deen";
let timeId = setInterval(() => {
setCount(count + 1);
username = username + count;
console.log("shows updated username ", username);
}, 1000);
React.useEffect(() => {
document.title = `Hello, ${username} ${count}`; //this updates title everytime but username is still old
}, [count]);
console.log("shows old instead of updated username ", username); //doesn't work.doesn't show updated username value
return <h1>{username}</h1>;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ReposGrid />, rootElement);
最佳答案
代码遵循正确的行为,让我解释一下:
- setInterval 被执行并在事件队列中排队。
- 请注意,此时其中的代码并未执行,而是延迟 1 秒后执行。
- 接下来输入
useEffect
函数。请注意,setInterval
内的代码仍未执行。 - 您可以使用
用户名
的先前/原始值更新此处的标题。 - 接下来,您将 console.log 用户名的先前值并将其返回到
header
标记内。
At this point, the code which was in event queue it put back on stack and executed (i.e., atleast after 1 sec).
setCount(count + 1)
被调用。由于状态变量已更新,因此useEffect
会被执行,函数的其余部分也会被执行(包括标题的更新)- 现在将执行下一条语句
username = username + count
。由于这不是状态变量,因此即使变量更新,也不会调用useEffect
,也不会更新document.title
。 - 现在用户名已更新(但没有副作用)。
- 接下来
console.log(“显示更新的用户名”,用户名)
- 这应该是 console.log 更新的值。
关于javascript - 为什么 setInterval 中更新的用户名没有反射(reflect)在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60872717/