简体   繁体   中英

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.

I created a reducer, connected react with redux and setup an action within component A - so far so good. But how do I listen to a state change inside of component 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?


What I've got so far for Component B - the receiving component:

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. So using the useEffect hook should fit your use case ( https://reactjs.org/docs/hooks-effect.html ).

Something like this in your example :

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

  return (...);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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