繁体   English   中英

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

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

我有一个问题,关于如何在一个组件中的一个函数改变一个不同组件的 reducer 值时触发。

我目前在我的Home组件中有一个在ComponentDidMount中运行的函数。 如果我的值this.props.reducer.run为真,函数就会触发。 初始状态设置为true因此该函数会在应用首次加载时触发。

在我的Profile组件中,我有一个切换开关,可以将this.props.reducer.run切换为truefalse 当减速器值发生变化时,是否可以在Home触发我的功能?

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

主页.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)
}
...

是的,您可以使用componentDidUpdate做到这一点。 componentDidUpdate被调用时,它将传递组件 props 的前一个值(我们称之为prevProps )。 通过将prevProps.reducer.runthis.props.reducer.run进行比较,您可以确定值是否更改,如果更改,则相应地调用您的函数。

或者,如果这是一个功能组件,您可以使用useEffect实现相同的useEffect

暂无
暂无

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

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