700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > React报错Warning: This synthetic event is reused for performance reasons. If you‘re seeing this 解决方法

React报错Warning: This synthetic event is reused for performance reasons. If you‘re seeing this 解决方法

时间:2018-07-13 16:59:52

相关推荐

React报错Warning: This synthetic event is reused for performance reasons. If you‘re seeing this  解决方法

项目场景:

使用React的NavLink标签作为菜单列表,点击菜单列表按钮,动态更换菜单名称

问题描述

点击菜单NavLink时报错出现如下信息

Warning:This synthetic event is reused for performance reasons.If you're seeing this, you're accessing the property `nativeEvent` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist(). See https://fb.me/react-event-pooling for more information.

例子

// 其他无关紧要部分省略了<input onChange={event => {console.log(event.type) // changesetTimeout(() => {console.log(event.type) // null,并会出现以上警告})}} />

原因分析:

我们在react中操作的DOM事件,获取到的事件对象,其实是react内部帮我们合成的。为了节约性能,会使用对象池,当一个合成事件对象被使用完毕,即同步代码实现完毕后,会再次调用并且将其属性全部设为Null,所以当我们异步访问或者打印时,显示的属性值已经是null值

解决方案:

如果要以异步方式访问事件属性,应该对事件调用event.persist(),这将从池中删除合成事件,并允许用户代码保留对事件的引用。它会将当前的合成事件对象从对象池抽离出来,这样就不会再被调用并且其属性不会变为Null.

event事件对象传入方法,

<div onClick={(event) => this.mouseOut('关注QC班长',event)}><NavLink to="/largeScreen/fireworks/home" activeClassName={styles.activeNav}><SlackOutlined style={{ marginRight: '5px' }} />关注QC班长</NavLink></div>

在方法中调用event.persist()即可

mouseOut = (menuName,event) => {this.setState({ visible: 'none' })this.setState({ isActive: true })if (menuName !== '') {event.persist()// 从事件池中移除该合成函数并允许对该合成事件的引用被保留下来。this.setState({ activeMenuName: menuName })}}

参考文献

0、合成事件(SyntheticEvent) – React 中文文档 v16.6.3

1、react 合成事件关于event.persist()的报错_coderlin_的博客-CSDN博客

2、/p/bf390141fae8

3、/09/20 React中获取target(报错信息Warning: This synthetic event is reused for performance reasons.)_六月要好好加油呀的博客-CSDN博客

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。