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

时间:2019-02-07 00:59:28

标签: reactjs

此处的代码沙箱: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 个答案:

答案 0 :(得分: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"

有关综合事件的更多信息,请参见herehere

但是,如果您已经从event知道了您想要的内容,则可以像这样destructure设置其属性:

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

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