简体   繁体   English

通过在组件内部执行函数来响应 redux 状态的变化

[英]React to redux state changes by executing function inside of component

I'm currently trying to implement redux to my react-app for the first time.我目前正在尝试第一次在我的 react-app 中实现redux

I created a reducer, connected react with redux and setup an action within component A - so far so good.我创建了一个减速器,与 redux 连接反应并在组件 A 中设置一个动作 - 到目前为止一切顺利。 But how do I listen to a state change inside of component B?但是我如何监听组件 B 内部的状态变化呢?

Something like this:像这样的东西:

changes.subscribe(value => {
   if (value === 1) {
       this.runSpecificFunction();
   } 
});

In other words, I want to subscribe to the changes, and react to them by executing some functions inside of component B. How can I do so?换句话说,我想订阅更改,并通过执行组件 B 内部的一些函数来对它们做出反应。我该怎么做?


What I've got so far for Component B - the receiving component:到目前为止我对组件 B 的了解 - 接收组件:

const mapStateToProps = state => {
    return {
        nav: state.navigation
    };
};

export default connect(mapStateToProps)(withRouter(CartHolder));

Reducer:减速器:

const initialState = {
    navigation: 0 // inactive
};

const rootReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'START_NAVIGATION':
            return {
                navigation: action.value
            };
        case 'STOP_NAVIGATION':
            return {
                navigation: action.value
            };
        default:
            return state
    }
};

export default rootReducer;

Any state change (redux based or not) will re-render your child component.任何状态更改(是否基于 redux)都将重新渲染您的子组件。 So using the useEffect hook should fit your use case ( https://reactjs.org/docs/hooks-effect.html ).因此,使用useEffect钩子应该适合您的用例( https://reactjs.org/docs/hooks-effect.html )。

Something like this in your example :在你的例子中是这样的:

const CartHolder = () => {
  React.useEffect(() => {
    myCallbackFunction(nav);
  }, [nav]);

  return (...);
};

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

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