简体   繁体   中英

Redux: Notify parent React component when the child component dispatches a Redux action

My parent component is a React class that has a method in it which does a setInterval (amongst other things). This interval is cleared when some conditions are met.

However I want this method on the parent React class to be called once again when one of it's children dispatches a specific action (thereby re-setting the setInterval ).

How do I notify the parent that the child had dispatched a certain (Redux) action? I'm using connect to pass the state down. So the parent and the children share the same dispatch method.

Not sure if that would be the optimal solution for your problem, but how about passing down a callback to the child component and dispatching the redux action from the parent? You would be able to clear the interval there too.

Actually you can pass send action method from parent to child, call it in child component like this.props.someMethodToDispatch() and do something with it in parent component before you dispatch action. For example:

 const dispatch = (action) => console.info("Action dispatched", action); class Parent extends React.Component { constructor(props) { super(props); this._handleChildClick = this._handleChildClick.bind(this); } _handleChildClick(action) { // You can do something here console.info("Child pass action", action); // And after that dispatch action dispatch(action); } render() { return ( <div> <h2>Simulate handle action from child</h2> <Child handleClick={this._handleChildClick} /> </div> ); } } class Child extends React.Component { _generateAction() { // This is action creator mock return {type: "SOME_ACTION", payload: "someting"}; } render() { return (<button onClick={() => this.props.handleClick(this._generateAction())}>Click me</button>); } } ReactDOM.render(<Parent />, document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

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