如何响应 redux 中的状态变化并派发另一个动作?

How to respond to state change in redux and dispatch another action?

谁能告诉我如何使用 react-redux 执行以下操作:

组件 A 调度更新状态的操作(异步)

组件 B(不是 A 的子组件)需要能够检测状态何时更改并调度另一个操作。

我的问题是当我尝试在组件 B 中执行 dispatch action 2 时,状态仍处于初始状态并且没有更新。

我也尝试过在 componentWillUpdate 中调度操作 2,但是,这会创建一个无限循环,因为第二个操作也会更新状态(并且也是异步的)

大致是这样的:

//----- Component A
class ComponentA extends React.Component {
  constructor(props) {
    super(props);
    this.props.dispatch(loadEvents()); // loadEvents is async and will   update state.eventsState
  }
}

const mapStateToProps = function (state) {
  return {
    eventsState: state.eventsState,
  };
};

export default connect(mapStateToProps)(ComponentA);


//----- Component B
class ComponentA extends React.Component {
  constructor(props) {
    super(props);
    props.dispatch(getEventUsers(props.eventsState.eventId)); // the eventsState is in initial state here (empty)...where do I call getEventUsers?
  }

  componentWillUpdate(nextProps) {
    nextProps.dispatch(getEventUsers(props.eventsState.eventId)) // Creates an infinite loop, getEventUsers also updates state
  }
}

const mapStateToProps = function (state) {
  return {
    eventsState: state.eventsState,
  };
};

export default connect(mapStateToProps)(ComponentA);

如果不查看您的 Redux 代码,我会说您的组件 B 在构造函数中获取空数据,因为它大约在组件 A 的同时实例化,此时异步请求由组件 A 构造函数发起仍在进行中。

当异步请求完成时,你的 Redux 应该触发一个包含接收到的数据的动作。然后你的减速器将这些数据放入状态,这反过来会改变你连接的组件的道具并强制它们重新渲染。

您应该仅在 props.eventState.eventId 存在且已更改时调度 getEventUsers。