简体   繁体   中英

React setState in componentDidMount not working

Any idea why following setState for popUpBurned is not working?

 componentDidMount() {
    const { user } = this.props
    const { popUpBurned } = this.state
    const visits = user.visitsCounter

    if (visits === 6 && !popUpBurned) {

      this.setState({ popUpBurned: true })
      this._popupFeedbackVisits.show()
    }

  }

I need my _popupFeedbackVisits to trigger only once when the visit-number is 6, which works just fine. But when in the same visit, the user navigates to another page and comes back to dashboard, the popup triggers again (as the visits are still 6).

How can I make the popup to trigger once and only once? My though was to add that boolean, but it does not seems to work inside componentDidMount. What am I missing?

Thanks!

My suggestion would be to store the popUpBurned somewhere else and pass it in as a prop to this component. It seems like from your post user is a global object and this should only ever happen once. Perhaps storing this on the user would be appropriate?

componentDidMount() {
    const { user } = this.props
    const visits = user.visitsCounter
    const popUpBurned = user.popUpBurned

    if (visits === 6 && !popUpBurned) {

      this.setState({ popUpBurned: true })
      this._popupFeedbackVisits.show()
    }
}

If popUpBurned is not used in render , it probably doesn't need to be in state and you could make it a class property:

class ... extends React.Component {
    constructor(props) {
        ...
        this.popUpBurned = false
    }

    ...

    componentDidMount() {
        const { user } = this.props
        const visits = user.visitsCounter

        if (visits === 6 && !this.popUpBurned) {
            this.popUpBurned = true
            this._popupFeedbackVisits.show()
        }

    }
}

You can try changing the visit number in if statement, so that it does not trigger the related function again. Because in any refresh or coming back to the page will make componentDidMount work, and then it continues to popup.

This work-around using sessionStorage solved the issue:

if (user.visitsCounter === 6 && !sessionStorage.getItem('popUpBurned')) {
      sessionStorage.setItem('popUpBurned', true)

      this._popupFeedbackVisits.show()
    }

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