Reputation: 4043
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;
Upvotes: 0
Views: 685
Reputation: 119
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 (...);
};
Upvotes: 1