首页 > 其他分享 >[React] Flushing state updates synchronously with flushSync

[React] Flushing state updates synchronously with flushSync

时间:2023-03-20 22:11:49浏览次数:48  
标签:current DOM update flushSync React state

In React, every update is split in two phases:

  • During render, React calls your components to figure out what should be on the screen.
  • During commit, React applies changes to the DOM.

React sets ref.current during the commit. Before updating the DOM, React sets the affected ref.current values to null. After updating the DOM, React immediately sets them to the corresponding DOM nodes.

 

In React, state updates are queued.

setTodos([ ...todos, newTodo]);
listRef.current.lastChild.scrollIntoView();

setTodos does not immediately update the DOM.

So the time you scroll the list to its last element, the todo has not yet been added. This is why scrolling always “lags behind” by one item.

 

To fix this issue, you can force React to update (“flush”) the DOM synchronously. To do this, import flushSync from react-dom and wrap the state update into a flushSync call:

flushSync(() => {
  setTodos([ ...todos, newTodo]);
});
listRef.current.lastChild.scrollIntoView();

This will instruct React to update the DOM synchronously right after the code wrapped in flushSync executes.

 

标签:current,DOM,update,flushSync,React,state
From: https://www.cnblogs.com/Answer1215/p/17238093.html

相关文章

  • Katalon使用自定义关键字实现下载(Assert Statement)
    该图是完整的下载流程: 操作步骤如下: 1.在keywords-testclass(右键-new-keyword)-myKeywords(输入名称,不选择任何筛选项,点击报错)   mykeywords文件下输入js代码:packagetes......
  • #yyds干货盘点 【React工作记录二十七】moment处理日期格式
     目录​​前言​​​​导语​​​​解决思路​​​​总结​​前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五......
  • #yyds干货盘点 【React工作记录二十八】重置ant design得样式
     目录​​前言​​​​导语​​​​代码部分​​​​总结​​前言我是歌谣我有个兄弟巅峰的时候排名c站总榜19叫前端小歌谣曾经我花了三年的时间创作了他现在我要用五......
  • 直播平台软件开发,React onDrop拖拽事件
    直播平台软件开发,ReactonDrop拖拽事件拖拽节点时传递数据,拖拽事件触发时目标节点为边框闪动样式 拖拽节点 <divid={'ChartListItem'+deepItem.selectId}  cl......
  • React基础 - JSX
    //导入React、React-DOM//React负责创建React元素-虚拟DOM//ReactDOM负责渲染React元素//JSX-插值表达式//表达式//1.变量//2.基本数据类型:string、num......
  • Cannot use import statement outside a module
    参考资料:https://www.jianshu.com/p/60a8a74f5eee?ivk_sa=1024320u 使用vscode调试js代码,出现如上报错解决过程:npminit-y在package.json中添加字段typepackage.js......
  • vue、react 技术栈和生态
     vue技术栈和生态Vue是一个流行的JavaScript前端框架,它具有易学易用、高效灵活等特点。Vue技术栈包括以下内容:Vue:Vue框架本身,提供了组件化、响应式等核心特性......
  • 2023-03-20 React: Each child in a list should have a unique "key" prop. Check t
    Eachchildinalistshouldhaveaunique"key"prop. Checktherendermethodof`App`列表中的每个孩子都应该有一个唯一的“关键”道具。检查`App的呈现方法`前......
  • 关于写计算属性时的mapState
    1.普通的计算属性返回state中数据时,都要加this.$store.state.xxxcomputed:{categoryList(){returnthis.$store.state.home.categoryList;}}如果......
  • 谈谈 Vue shallowRef 和 shallowReactive
    深层次响应式reactive和ref创建的对象都是深层次的,对象的根属性和嵌套属性都是响应式的。深层次转换是递归地转为响应式,对象里的每个属性访问都将触发代理的依赖追踪,......