Javascript React Native-如何基于reducer值的更改触发函数?
我有一个问题,关于如何在一个组件中触发一个函数,以根据不同组件的减速机值进行更改 我当前在我的Javascript React Native-如何基于reducer值的更改触发函数?,javascript,reactjs,react-native,redux,react-lifecycle-hooks,Javascript,Reactjs,React Native,Redux,React Lifecycle Hooks,我有一个问题,关于如何在一个组件中触发一个函数,以根据不同组件的减速机值进行更改 我当前在我的主页组件中有一个函数,它在组件安装中运行。如果my valuethis.props.reducer.run为true,则函数将启动。初始状态设置为true,以便在应用程序首次加载时启动该函数 在我的Profile组件中,我有一个切换开关,可以切换this.props.reducer.run到true或false。当减速器值发生变化时,是否可以在Home中触发my函数 下面是我的代码模型,我想知道comp
主页
组件中有一个函数,它在组件安装
中运行。如果my valuethis.props.reducer.run
为true,则函数将启动。初始状态设置为true
,以便在应用程序首次加载时启动该函数
在我的Profile
组件中,我有一个切换开关,可以切换this.props.reducer.run
到true
或false
。当减速器值发生变化时,是否可以在Home
中触发my函数
下面是我的代码模型,我想知道componentdiddupdate
是否是我应该看到的,如果是这样,请提供一些指导:
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)
}
...
是的,您可以使用
componentdiddupdate
执行此操作。调用componentdiddupdate
时,它将被传递组件属性的上一个值(我们称之为prevProps
)。通过比较prevProps.reducer.run
与this.props.reducer.run
,可以确定值是否更改,如果更改,则相应地调用函数
或者,如果这是一个功能组件,您可以使用useffect
实现同样的功能