0
React+异步任务 的疑问
source link: https://www.v2ex.com/t/809458
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
背景:Vue 用户,重学 React 中
function App() {
const afterRender = () => {
console.log('after render')
}
// 1. 渲染后回调
// useEffect(afterRender)
// 2. 尝试用异步方式模拟渲染后的回调
queueMicrotask(afterRender)
// Promise.resolve().then(afterRender)
// setTimeout(afterRender, 0)
return (
<div className="App">
<div>something</div>
</div>
)
}
问题在于:
useEffect 表现正常(废话),
而 2 中的 3 种方法,通过异步方式实现渲染后执行,afterRender 会被调用两次,即控制台打印两次after render
,
这到底是什么原因?
第 1 条附言 · 6 小时 12 分钟前
已解决,react 版本 17,关掉 Strict Mode 成功解决。谢谢各位!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK