React Hook中useState更新延迟问题

方法一:  去掉useEffect的第二个参数

例如以下代码 错误实例


   
   
  1. const[zoom, setZoom] = useState( 0);
  2. useEffect(() = >{
  3. document.getElementById( 'workspace-content').addEventListener( 'mousewheel', scrollFunc);
  4. },[]);
  5. function scrollFunc(e) {
  6. setZoom(zoom + 5)
  7. }

会出现zoom永远等于 0+5, 而不是所谓的5, 10 ,15 为什么会这样呢? 因为useEffect执行时,会创建一个闭包,在每次监听到mousewheel运行时 闭包内部保存了zoom的初始化值 每次调用的时候都是取的初始化值0 所有会一直为0+5

怎么解决呢?

解决方案: 去掉useEffect中的空数组即可


   
   
  1. const[zoom, setZoom] = useState( 0);
  2. useEffect(() = >{
  3. document.getElementById( 'workspace-content').addEventListener( 'mousewheel', scrollFunc);
  4. return () = > document.getElementById( 'workspace-content').removeEventListener( "mousewheel", scrollFunc); // 记得解绑事件
  5. });
  6. function scrollFunc(e) {
  7. setZoom(zoom + 5)
  8. }

方法二: 将改变函数移入useEffect并将第二个参数设置为state

依旧用上面的例子

解决方法: 正确示例


   
   
  1. useEffect(() = >{
  2. document.getElementById( 'workspace-content').addEventListener( 'mousewheel', scrollFunc);
  3. return () = > document.getElementById( 'workspace-content').removeEventListener( "mousewheel", scrollFunc);
  4. function scrollFunc(e) {
  5. setZoom(zoom + 5) e.preventDefault()
  6. }
  7. },[zoom]);

方法三: 如果不在意视图实时渲染 采用Ref代替useState或者全局变量

例如下面的代码 错误示例


   
   
  1. const [currentIndex, setCurrentIndex] = useState( 0)
  2. const handleLeft = () => {
  3. setCurrentIndex(currentIndex+ 1)
  4. console.log(currentIndex)
  5. }

初始化currentIndex为0 每次执行handleLeft函 数是让currentIndex加1, 之后立即获取currentIndex的值发现 第一次执行currentIndex = 0

第二次执行currentIndex = 1 每次都跟实际情况差一个  查阅资料发现useState必须要执行完react整个生命周期才会获取最新值

解决方案: 用useRef代替


   
   
  1. const currentIndexRef = useRef( 0); // 不能用useState 会导致数据更新不及时
  2. const handleLeft = () => {
  3. currentIndexRef.current += 1
  4. console.log(currentIndexRef.current)
  5. }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值