【发布时间】:2020-10-16 19:32:58
【问题描述】:
我有一个问题,关于如何在一个组件中触发一个函数,以改变来自不同组件的 reducer 值。
我目前在我的Home 组件中有一个在ComponentDidMount 中运行的函数。如果我的值 this.props.reducer.run 为 true,则函数触发。初始状态设置为true,因此该函数会在应用首次加载时触发。
在我的Profile 组件中,我有一个拨动开关,可以将this.props.reducer.run 切换到true 或false。当reducer值发生变化时,是否可以在Home触发我的函数?
下面是我拥有的代码的模型,我想知道 ComponentDidUpdate 是否是我应该查看的内容,如果是的话,将不胜感激:
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)
}
...
【问题讨论】:
标签: javascript reactjs react-native redux react-lifecycle-hooks