【发布时间】:2016-02-10 12:37:24
【问题描述】:
换句话说,如何在中继突变时更新本地状态(通量存储,例如 ModalStore、HistoryStore 等)。我能找到的唯一解决方案是使用回调来触发通量操作。然而,这变得非常多余和危险,因为每次使用突变时我都必须触发一个动作,并且那段代码取决于突变有效负载的形状。我有一种我不知道的更好的解决方案的感觉。
【问题讨论】:
标签: reactjs flux reactjs-flux graphql relayjs
换句话说,如何在中继突变时更新本地状态(通量存储,例如 ModalStore、HistoryStore 等)。我能找到的唯一解决方案是使用回调来触发通量操作。然而,这变得非常多余和危险,因为每次使用突变时我都必须触发一个动作,并且那段代码取决于突变有效负载的形状。我有一种我不知道的更好的解决方案的感觉。
【问题讨论】:
标签: reactjs flux reactjs-flux graphql relayjs
在前往服务器之前,每个突变都会经过网络层的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);
【讨论】: