ReactJS can't set state from an event with event.persist()

前端 未结 5 983
予麋鹿
予麋鹿 2020-12-08 00:15

I need to set a state field which I get from an event, but it doesn\'t get set when I pass a function to it. The component and method looks like the following:



        
5条回答
  •  不知归路
    2020-12-08 01:08

    With the comment from @thirtydot I got a working solution.

    I think it's because setState is "async", so by the time the function you pass to setState is executed (and the event is accessed), the event is no longer around. In the second version, the event is accessed immediately and its currentTarget passed to setState

    So I stored the event.currentTarget to a variable and used that as it's explained in the ReactJs Event Pooling

    Looks like this and it works

    private toggleFilter = (event: any) => {
            let target = event.currentTarget;   
            this.setState((prevState) => ({
                isFiltering: !prevState.isFiltering,
                anchor: target
            }));
        }
    

    However this does not explain why event.persist() is not working. I'll accept the answer which explains it.

提交回复
热议问题