ReactJS + Flux: action is taken twice when I route between components

I am working with my little app built with React, Router and Flux.
I have 2 routes:

<Route path="/" exact component={Board} />
<Route path="/table" component={Table} />

      

and the map component displayed inside the board. The card has an onClick event that dispatches an action for the Store, which fires a "cardClicked" event. The Board component listens for these activities and does some things:

//Board.js:
componentWillMount() {
    GameStore.on("cardClicked", () => {
      console.log("received click action")
    })

  }

      

Everything works fine, but when I go to the Table component and then back to Board and fire onClick on Card, the app crashes. I found out that the Board listens for this "cardClicked" event "twice" (this "clicked received" message appears twice on each click). If I go to the table again and go back to the board again, the message appears three times, etc., as if every time the Board component mounts it, it adds another "function" to listen for the "cardClicked" event.

How can this be prevented? Is there some function to make the component stop listening for this event when it disconnects and then starts listening again when it mounts?

+3


source to share


1 answer


You add a listener when the component is mounted, but you never remove it. Each time this component is mounted, it runs the method componentWillMount

, adding a new listener. Nothing in the code will remove them, so it makes sense that they will accumulate.



You can use the componentWillUnmount component lifecycle method to remove the event listener, which should solve the multi-event issue. However, I don't understand why this should cause a crash of any kind, so you most likely have another undiscovered problem.

0


source







All Articles