简体   繁体   English

React Native - 如何根据减速器值的变化触发函数?

[英]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.我有一个问题,关于如何在一个组件中的一个函数改变一个不同组件的 reducer 值时触发。

I currently have a function in my Home component that runs in ComponentDidMount .我目前在我的Home组件中有一个在ComponentDidMount中运行的函数。 If my value this.props.reducer.run is true the function fires.如果我的值this.props.reducer.run为真,函数就会触发。 The initial state is set to true so the function fires when the app first loads.初始状态设置为true因此该函数会在应用首次加载时触发。

In my Profile component I have a toggle switch with toggles this.props.reducer.run to true or false .在我的Profile组件中,我有一个切换开关,可以将this.props.reducer.run切换为truefalse Is it possible to trigger my function in Home when a change to the reducer value occurs?当减速器值发生变化时,是否可以在Home触发我的功能?

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:下面是我拥有的代码的模型,我想知道ComponentDidUpdate是否是我应该查看的内容,如果是的话,将不胜感激:

Home.js主页.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 .是的,您可以使用componentDidUpdate做到这一点。 When componentDidUpdate is invoked, it will be passed the previous value of your component props (let's call this prevProps ).componentDidUpdate被调用时,它将传递组件 props 的前一个值(我们称之为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.通过将prevProps.reducer.runthis.props.reducer.run进行比较,您可以确定值是否更改,如果更改,则相应地调用您的函数。

Alternatively, if this were a functional component you could achieve the same with useEffect .或者,如果这是一个功能组件,您可以使用useEffect实现相同的useEffect

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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