简体   繁体   中英

ReactJS + Flux: Action received twice when I route between components

I work with my little app made with React, Router and Flux.
I've got 2 routes:

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

and Card component rendered inside Board. Card has onClick event sending an action to Store which emit event "cardClicked" . Board component listens to this actions and do some stuff:

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

  }

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

How to prevent that? Is there some function to make the component stop listening to this event when it will unmount and then start listening again when it will mount?

You are adding a listener when the component mounts, but you are never removing it. Every time this component mounts, it is going to run it's componentWillMount method, adding a new listener. Nothing in your code would ever remove them, so it makes sense that they would accumulate.

You can use the 'componentWillUnmount` lifecycle method to remove your event listener, which should resolve the issue of multiple events. That said, I don't see why this should be causing a crash of any sort, so you most likely have another undiscovered problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM