【问题标题】:Redux: Notify parent React component when the child component dispatches a Redux actionRedux:当子组件 dispatch Redux action 时通知父 React 组件
【发布时间】:2017-03-31 13:55:43
【问题描述】:

我的父组件是一个 React 类,其中有一个方法,该方法执行 setInterval(除其他外)。当满足某些条件时,此间隔将被清除。

但是,我希望在其中一个子级调度特定操作时再次调用父级 React 类上的此方法(从而重新设置 setInterval)。

如何通知父级子级已调度某个 (Redux) 操作?我正在使用connect 传递状态。所以父母和孩子共享相同的调度方法。

【问题讨论】:

  • 这听起来像是一种情况,您可能希望向您的状态添加一个属性,该属性在子组件调度操作时更新。你的父组件可以使用connect订阅这部分状态。

标签: javascript reactjs redux react-redux


【解决方案1】:

不确定这是否是您问题的最佳解决方案,但是如何将回调传递给子组件并从父组件调度 redux 操作?您也可以清除那里的间隔。

【讨论】:

    【解决方案2】:

    实际上,您可以将发送动作方法从父级传递给子级,在子组件中调用它,例如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>

    【讨论】:

      猜你喜欢
      • 2019-08-24
      • 2018-05-19
      • 2018-09-03
      • 2017-07-24
      • 2021-11-01
      • 2018-09-08
      • 2017-09-12
      • 1970-01-01
      • 2021-04-02
      相关资源
      最近更新 更多