代码之家  ›  专栏  ›  技术社区  ›  dwjohnston

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

  •  0
  • dwjohnston  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  4
  •   Matt Carlotta    6 年前

    你在试着 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"
    

    关于合成事件的更多信息可以找到 here 和 here

    然而,如果你已经知道你想从 ,那么你可以 destructure 其性质如下:

    const handleChange = ({ target: { value, name } }) => {
        console.log(name, value);
    
        const newForm = { ...form, [name]: value };
        updateForm(newForm);
      };