Redux:当子组件调度Redux动作时通知父组件React组件
问题描述:
我的父组件是一个React类,它有一个在其中执行setInterval
(除其他之外)的方法的React类。当满足一些条件时,该间隔被清除。Redux:当子组件调度Redux动作时通知父组件React组件
但是,我希望在父React类中的这个方法在它的一个孩子分派一个特定的动作(从而重新设置setInterval
)时再次被调用。
我该如何通知父母孩子已经发送了某个(Redux)操作?我正在使用connect
来传递状态。所以父母和孩子共享相同的派遣方法。
答
不知道这是否会成为您的问题的最佳解决方案,但如何将回调传递给子组件并从父组件调度redux动作?你也可以在那里清除间隔。
答
实际上,您可以将发送操作方法从父项传递给子项,在子组件中调用它,如this.props.someMethodToDispatch()
,并在派发操作之前在父项组件中执行某些操作。 例如:
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>
这听起来像是在那里你可能需要一个属性添加到您的状态时,子组件调度的行动,被更新的情况下。你的父组件可以使用'connect'来订阅这部分状态。 – adrice727