首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React事件处理程序上的控制台日志语句导致合成事件警告

React事件处理程序上的控制台日志语句导致合成事件警告
EN

Stack Overflow用户
提问于 2019-02-07 08:59:28
回答 1查看 2.5K关注 0票数 3

代码沙盒:https://codesandbox.io/s/0olpzq7n3n

这是一些非常简单的代码:

代码语言:javascript
复制
const Form = ({ form, updateForm }) => {
  const handleChange = (event, value) => {
    console.log(event, value);
    console.log(event.target.name, event.target.value);

    const newForm = { ...form, ...{ [event.target.name]: event.target.value } };
    updateForm(newForm);
  };

  return (
    <form>
      <input
        name="value1"
        value={form.value1}
        onChange={event => handleChange(event)}
      />
    </form>
  );
};

const Form1 = connect(
  state => ({ form: state.form1 }),
  dispatch => ({ updateForm: newForm => dispatch(updateFormOne(newForm)) })
)(Form);

function Home() {
  return (
    <div>
      <h2>? Welcome to the Home route</h2>
      <Form1 />
    </div>
  );
}

如果您在此方案中编辑表单输入,则会显示以下警告:

代码语言:javascript
复制
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 (shortend URL that StackOverflow doesn't like). 

如果我删除这些控制台日志语句,该警告将消失。

这是怎么回事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-07 11:09:00

您正在尝试console.log()一个异步合成事件,该事件在执行callback时被删除。如果您希望持久化该事件,则使用event.persist()

使用event.persist(),您可以看到所有的event属性:

代码语言:javascript
复制
ispatchConfig: Object
_targetInst: FiberNode
nativeEvent: InputEvent
type: "change"
target: <input name="value1" value="this is form a1"></input>
currentTarget: null
eventPhase: 3
bubbles: true
cancelable: false
timeStamp: 2926.915000000008
defaultPrevented: false
isTrusted: true
isDefaultPrevented: function () {}
isPropagationStopped: function () {}
_dispatchListeners: null
_dispatchInstances: null
isPersistent: function () {}
<constructor>: "SyntheticEvent"

有关合成事件的更多信息,请访问herehere

但是,如果您已经知道希望从event获得什么,则可以像这样对其属性执行destructure操作:

代码语言:javascript
复制
const handleChange = ({ target: { value, name } }) => {
    console.log(name, value);

    const newForm = { ...form, [name]: value };
    updateForm(newForm);
  };
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54564863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档