splunk
splunk

Reputation: 6815

call function when routing from a scene to another one

I'm using react-native-router-flux and this is my routing piece of code:

<Router navigationBarStyle={navBar} sceneStyle={{ paddingTop: 53}}>
  <Scene key="main">       
    <Scene
      key="firstPage"  
      component={FirstPage}
      initial
    />

    <Scene 
      key="secondPage"
      component={SecondPage}
    />
  </Scene>
</Router>

This is a part of FirstPage component:

class FirstPage extends Component {
  constructor(props) {
    console.log("constructor");
    super(props);
  }

  componentWillMount(){
    console.log("COMPONENT WILL MOUNT");
  }

  componentDidMount(){
    console.log("COMPONENT DID MOUNT");
  }

  componentWillReceiveProps(){
    console.log("COMPONENT WILL RECEIVE PROPS");
  }

  shouldComponentUpdate(){
    console.log("SHOULD COMPONENT UPDATE")
  }

  componentDidUpdate(){
    console.log("COMPONENT DID UPDATE");
  }

  componentWillUnmount(){
    console.log("COMPONENT WILL UNMOUNT");
  }
}

Once I open my app FirstPage component is loaded and I get this by console.logs:

COMPONENT WILL MOUNT
COMPONENT DID MOUNT
SHOULD COMPONENT UPDATE

When I click a button that sends me to secondPage key, loading SecondPage, component console.logs give me this:

COMPONENT WILL RECEIVE PROPS
SHOULD COMPONENT UPDATE

Until here, it's all Ok. What I'd like to have is to be able to trigger a function whenever I go back from SecondPage to FirstPage. When I go back to the FirstPage, the constructor, componentWillMount, componentDidMount etc... aren't triggered.

How do I go about this?

Upvotes: 1

Views: 579

Answers (1)

martinarroyo
martinarroyo

Reputation: 9701

This might seem a bit of an antipattern and also it might not suit your setup if you do not want to include a state container, but a suggestion would be to bind your app to a reducer that listens to changes in the current scene. For instance, with redux, you can easily do that by following the example in the docs.

Then, the reducer will be triggered everytime the app's scene changes, and with that information I think you can apply any custom logic. You should not do that in the reducer (that is where the antipattern bit is), but what you can do is pass that value to your component and observe the prop in componentWillReceiveProps or any other appropriate lifecycle method. By comparing nextProps with your current props, you can infer what the user did.

This is a bit hacky, but it might do the job.

Upvotes: 0

Related Questions