V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
pyplayer
V2EX  ›  JavaScript

Js 小白求问大佬们为何第八行 await 运行后 e 这个事件对象会变 null

  •  
  •   pyplayer · 2020-04-07 05:00:39 +08:00 · 2528 次点击
    这是一个创建于 1478 天前的主题,其中的信息可能已经有所发展或是发生改变。
    const clickZan = async function (e) {
        if (!token) {
          alert("请先登录");
        } else {
          console.log(e.target);
          const commentid = e.target.getAttribute("commentid");
          debugger;
          const result = await reqZan(token, commentid);
          e.target.className = "iconfont icon-zan red";
        }
      };
    
    6 条回复    2020-04-07 10:15:00 +08:00
    yyss8
        1
    yyss8  
       2020-04-07 05:38:26 +08:00 via iPhone
    断点里也是 null ? 如果只是 console 出来的是 null 那么可以深度复制一个 e 的内容 然后 console 那个 e
    des
        2
    des  
       2020-04-07 07:41:19 +08:00 via Android
    是 e.target 变成了 null 吧?
    e 变成 null 我觉得不太可能,建议把 e.target 首先赋值成一个变量
    pyplayer
        3
    pyplayer  
    OP
       2020-04-07 08:08:37 +08:00
    @des
    @yyss8
    e 确实没变 null e.target 变 null 了 后来先把 e.target 赋给 temp 是可以的,不过警告了
    arning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property `target` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().
    查了下 如果在 react 中想异步访问事件属性(如在 setTimeout 内),应该在是处理事件时调用 event.persist(),这会从事件池中移除该合成函数并允许对该合成事件的引用被保留下来
    des
        4
    des  
       2020-04-07 08:14:10 +08:00
    @pyplayer
    料到了是用了框架
    既然用了 React,那就走 React 流程,不建议自己操纵 dom
    rodjl
        5
    rodjl  
       2020-04-07 09:07:40 +08:00 via iPhone
    用了 react 吧?调用 e.persist()或者在 await 前用个变量保存 e.target
    zhw2590582
        6
    zhw2590582  
       2020-04-07 10:15:00 +08:00   ❤️ 1
    react 内部是封装过事件对象的,事件对象是共用的,异步调用的情况下对象可能被释放或者重置,可以在异步之前缓存下 target 就可以了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3750 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:52 · PVG 08:52 · LAX 17:52 · JFK 20:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.