简体   繁体   中英

React Native - how do I trigger a function based off a change in a reducer value?

I have a question about how to trigger a function in one component on the change of a reducer value from a different component.

I currently have a function in my Home component that runs in ComponentDidMount . If my value this.props.reducer.run is true the function fires. The initial state is set to true so the function fires when the app first loads.

In my Profile component I have a toggle switch with toggles this.props.reducer.run to true or false . Is it possible to trigger my function in Home when a change to the reducer value occurs?

Below is a mock up of the code i have, i am wondering if ComponentDidUpdate is what I should be looking at, if so some guidance would be appreciated:

Home.js

...

myFunction() = > {
   console.log('fired')
}

ComponentDidMount() {
   //runs on load
   if(this.props.reducer.run == true) {
     this.myFunction()
   }
}

...


**Profile.js**

...

toggleRun = () => {
   this.props.setRun(!this.props.reducer.run)
}
...

yes, you can do this with componentDidUpdate . When componentDidUpdate is invoked, it will be passed the previous value of your component props (let's call this prevProps ). By comparing the prevProps.reducer.run to this.props.reducer.run , you can determine if the value changed and, if it did, call your function accordingly.

Alternatively, if this were a functional component you could achieve the same with useEffect .

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