如何为RelayMutations触发Flux操作

时间:2015-11-09 19:07:47

标签: reactjs flux reactjs-flux graphql relayjs

换句话说,如何在继电器突变时更新本地状态(磁通存储,如ModalStore,HistoryStore等)。我能找到的唯一解决方案是使用回调来激发助焊剂动作。然而,这变得非常冗余和危险,因为每次使用突变时我都必须触发一个动作,并且该段代码取决于变异有效载荷的形状。我觉得有一个更好的解决方案,我不知道。

1 个答案:

答案 0 :(得分:1)

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

假设对于名为FooMutation的每个单个Relay突变,你有三个相应的Flux动作叫做RelayMutationActions.(doOptimistic|commit|rollback)FooMutation,这样的事情可能有效:

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);