英文:
React flushSync() isn't working as expected
问题
以下是您要翻译的内容:
"我清楚以下做法并不好。然而,我想知道为什么在我点击按钮后,如果我使用 flushSync()
,这段代码片段不起作用。
当我说它不起作用时,我是指警报显示为“你好,!”并且在随后的点击中,它显示先前的状态而不是当前的状态。"
export default function FeedbackForm() {
const [name, setName] = useState('');
function handleClick() {
flushSync(() => {
setName(prompt('What is your name?'))
})
alert(`Hello, ${name}!`);
}
return (
<button onClick={handleClick}>
Greet
</button>
);
}
英文:
I am clear that the following is not a good practice. However, I would like to know why this snippet is not working after I click on the button if I'm using flushSync()
.
When I say that it is not working, I'm referring to the fact that the alert is showing "Hello, !" and during subsequent clicks, it shows the previous state instead of the current one.
export default function FeedbackForm() {
const [name, setName] = useState('');
function handleClick() {
flushSync(() => {
setName(prompt('What is your name?'))
})
alert(`Hello, ${name}!`);
}
return (
<button onClick={handleClick}>
Greet
</button>
);
}
答案1
得分: 3
在阅读了这里和那里之后,我得出了以下结论:
React 使用 flushSync()
强制更新DOM,但这并不意味着它会立即更新状态变量(name
),因为我们知道,React 是异步更新状态的。
这种方法更适用于 如果你想从DOM中获取一些更新后的信息,但需要首先设置一个状态。
总之,文档建议只在绝对必要的情况下使用这种方法。
英文:
After reading here and there, I arrived at the following conclusion:
React forces the update of the DOM using flushSync()
, but this doesn't mean it also updates the state variable (name
) immediately because, as we know, React updates the state asynchronously.
This approach would be more suitable if you want to obtain some updated information from the DOM, but you need to set a state first.
Anyways, the documentation advises against using this method unless it is absolutely necessary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论