Kelvin
Kelvin

Reputation: 903

How to detect navigator pop with callback

I am currently dealing with some problem using React Native. This is the scenario: I have page A with a list of clickable page, when I click a page, let's say page B, I can setState({page: 'B'}) in page A and push the current navigator to page B, and when I pop the navigator back to page A, I would like to setState({page: ''}) in page A. However, I currently have no way to detect that the route has been pop to page A back, therefore I don't know where to put the setState code. Is there any method that I am missing?

Upvotes: 0

Views: 2089

Answers (1)

BradByte
BradByte

Reputation: 11093

You could pass a function into the routed component that would be called in componentWillUnmount.

// in your list component, this really depends on how you set up your
// Navigator to handle props, hopefully this will give you an idea of how it could work

this.props.navigator.push(someRoute, {onUnmount: () => this.setState({page: ''})}

// then, in the routed component

componentWillUnmount() {
  this.props.onUnmount()
}

Upvotes: 4

Related Questions