【问题标题】:Dispatching an action from another action从另一个动作分派一个动作
【发布时间】:2018-04-18 19:51:15
【问题描述】:

假设我有这些 Flux 操作;

{
  "type": "USER_LOADED",
  "payload": { ... }
}
{
  "type": "USER_LOAD_FAILED",
  "payload": { ... }
}
{
  "type": "SHOW_ERROR_MODAL",
  "payload": { ... }
}
{
  "type": "HIDE_ERROR_MODAL"
}

我有一个UserStore(监听USER_LOADEDUSER_LOAD_FAILED 并相应更新)和一个ModalStore(监听SHOW_ERROR_MODAL 并相应更新)。

我有一个始终出现在页面上的Modal 组件,它呈现来自ModalStore 的内容。

USER_LOAD_FAILED 发生时显示错误模式的最佳方式是什么?应该由ModalStore听吗?我最终会得到很多不同类型的 *_LOAD_FAILED 操作,这是个好主意吗?

我无法从UserStore 发送回复USER_LOAD_FAILED,因为您无法在发送期间发送。

可以从一些“控制器”组件中调度,该组件按照这些方式执行某些操作;

class UserController extends PureComponent {
  constructor(...args) {
    super(...args);

    this.state = { error: null, notified: false };
  }

  componentDidMount = () => this.props.flux.store('UserStore').on('change', this.onUserChange)

  componentDidUpdate = () => {
    if (this.state.error && !this.state.notified) {
      this.props.flux.actions.showErrorModal(this.state.error);

      this.setState({ notified: true });
    }
  }

  componentWillUnmount = () => this.props.flux.store('UserStore').off('change', this.onUserChange)

  onUserChange = () => {
    const userStore = this.props.flux.store('UserStore');

    // UserStore#getError() returns the most recent error which occurred (from USER_LOAD_FAILED).
    const error = userStore.getError();

    this.setState({ error, notified: error !== this.state.error });
  }

  render = () => ...
}

但我觉得这只是一种解决方法,而不是实际的解决方案。


我想到的最后一种方法是在最初发送 USER_LOAD_FAILED 的动作创建者中发送 SHOW_ERROR_MODAL,但我仍然不知道这是否是“建议”方式,因为您最终可能会提出其他情况下有很多逻辑。

【问题讨论】:

    标签: reactjs flux reactjs-flux


    【解决方案1】:

    如果您使用 Promises 进行 API 调用,如果您在 resolve 或 reject 函数中调度操作,则不会在当前调度期间触发。

    回调也是如此。当您的解析/拒绝/回调函数执行时,您的原始调度将完成。

    话虽如此,我不确定您为什么选择让您的模态组件由商店驱动。在显示模态之前,您是否进行了任何 API 调用或进行了一些其他处理?如果没有,也许您可​​以考虑根据组件的状态显示/隐藏模式。

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2020-08-27
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多