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

2020-04-07 05:00:39 +08:00
 pyplayer
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";
    }
  };
2535 次点击
所在节点    JavaScript
6 条回复
yyss8
2020-04-07 05:38:26 +08:00
断点里也是 null ? 如果只是 console 出来的是 null 那么可以深度复制一个 e 的内容 然后 console 那个 e
des
2020-04-07 07:41:19 +08:00
是 e.target 变成了 null 吧?
e 变成 null 我觉得不太可能,建议把 e.target 首先赋值成一个变量
pyplayer
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
2020-04-07 08:14:10 +08:00
@pyplayer
料到了是用了框架
既然用了 React,那就走 React 流程,不建议自己操纵 dom
rodjl
2020-04-07 09:07:40 +08:00
用了 react 吧?调用 e.persist()或者在 await 前用个变量保存 e.target
zhw2590582
2020-04-07 10:15:00 +08:00
react 内部是封装过事件对象的,事件对象是共用的,异步调用的情况下对象可能被释放或者重置,可以在异步之前缓存下 target 就可以了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/659966

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX