Warning: This synthetic event is reused for performance reasons happening with <input type=“checkbox” />

后端 未结 5 755
故里飘歌
故里飘歌 2021-01-31 07:25

I\'ve been working on a simple react-redux todo example for a class and I came across several warning messages that show in the console everytime I check and uncheck a checkbox

5条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 08:02

    This may be a little late, but I just came across the same problem and solved in a way that I think might be better than Adam Orlov's answer. I don't believe either answer is directly applicable to the asked question, but this comes up when googling about synthentic events and checkboxes so it's as good a place as any...

    I believe Adam is correct in his belief that React will essentially clear all properties of the SyntheticEvent object (which makes sense, since React is telling us that it's reusing the object).

    However, unless you need the entire object, I don't think calling event.persist() is the best solution, as according to the documentation, that will remove the object from the pool (presumably they put it there for a good reason).

    If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

    Instead of doing this, if you only need one or two values from the event object, you can just assign those to local variables, and then reference the local variables inside your own function, like this:

     {
        let checked = event.currentTarget.checked; //store whatever values we need from from the event here
        this._someOtherFunction(checked)
    } />
    

    In this way, you don't have to restructure your code in any way to avoid doing anything async that relies on event data, and you also don't have to worry about potential performance impacts as you allow React to do what it wants with the event pool.

提交回复
热议问题