如何为 RelayMutations 触发 Flux 动作

How to fire Flux actions for RelayMutations

换句话说,我怎样才能让本地状态(流量存储,如 ModalStore、HistoryStore 等)在中继突变时更新。我能找到的唯一解决方案是使用回调来触发通量操作。然而,这变得非常多余和危险,因为每次使用该突变时我都必须触发一个动作,并且那段代码取决于突变有效载荷的形状。我觉得有一个我不知道的更好的解决方案。

在前往服务器之前,每个突变都会通过网络层的 sendMutation 方法。一种解决方案可能是在那里拦截突变,然后触发乐观、提交和回滚 Flux 操作。

假设对于名为 FooMutation 的每个 Relay 突变,您都有三个相应的名为 RelayMutationActions.(doOptimistic|commit|rollback)FooMutation 的 Flux 动作,这样的事情可能会起作用:

var myNetworkLayer = {
  ...Relay.DefaultNetworkLayer,
  sendMutation(mutationRequest) {
    // Pluck the mutation from the outgoing request
    const mutation = mutationRequest.getMutation();
    const mutationName = mutation.getName();
    const mutationPayload = mutation.getVariables().input;

    // Fire an optimistic Flux action immediately
    RelayMutationActions[`doOptimistic${mutationName}`](mutationPayload);

    // Pass the request on to the default network layer implementation
    return Relay.DefaultNetworkLayer.sendMutation(mutationRequest)
      .then(payload =>
        if (payload.hasOwnProperty('errors')) {
          // If there was an error, fire a new rollback Flux action
          RelayMutationActions[`rollback${mutationName}`](payload);
        } else {
          // Otherwise fire a Flux action that commits the transaction
          RelayMutationActions[`commit${mutationName}`](payload);
        }
      );
  },
};
Relay.injectNetworkLayer(myNetworkLayer);