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

IT技术 reactjs
2021-04-27 18:08:47

代码沙箱在这里:https : //codesandbox.io/s/0olpzq7n3n

这是一些非常直接的代码:

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>
  );
}

如果您在这种情况下编辑表单输入,它会给出以下警告:

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). 

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

这里发生了什么事?

1个回答

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

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

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"

可以在此处此处找到有关合成事件的更多信息

但是,如果您已经知道从 中想要什么event,那么您可以像这样解构它的属性:

const handleChange = ({ target: { value, name } }) => {
    console.log(name, value);

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