Web Application with Redux,如何处理只需要执行一次的逻辑
Web Application with Redux, how to deal with logic only needs to execute once
说我们正在使用带有 redux 的 mvvm 框架,每次商店分派一个动作,我都会将我的组件更新为
Store.subscribe(() => {
var { Order, Payment } = Store.getState():
this.order = Order;
this.payment = Payment;
this.setCountDown(Order.leftTime);
this.checkIsPaymentValid(Payment);
});
这里,setCountDown
&checkIsPaymentValid
只需要执行一次,以后就不会再调用了。结果,我目前正在向组件添加状态,它变得像旧的 jquery 方式,变成类似于下面的内容:
switch(Order.status) {
case ORDER_STATUS_NORMAL:
break;
case ORDER_HAS_SET_COUNTDOWN:
break;
}
对处理这种情况有什么建议吗?
我建议您在处理程序的末尾取消抄写。来自 redux docs:
To unsubscribe the change listener, invoke the function returned by subscribe.
因此,您可以拆分处理程序并始终更改 this.order
和 this.payment
,但只调用一次 setCountDown
和 checkIsPaymentValid
:
Store.subscribe(() => {
var { Order, Payment } = Store.getState():
this.order = Order;
this.payment = Payment;
});
const unsubscribe = Store.subscribe(() => {
var { Order, Payment } = Store.getState():
this.setCountDown(Order.leftTime);
this.checkIsPaymentValid(Payment);
unsubscribe();
});
如果您需要根据操作而不是当前状态执行某些逻辑,这通常表明它应该作为调度操作的一部分发生。换句话说,在 dispatch()
之前或之后而不是在更改处理程序中执行这些副作用。
如果此逻辑跨越多个组件,您可能需要考虑使用 Redux Saga 之类的东西,它可以让您定义长 运行 可以“采取”行动并执行某些方面的“sagas”效果或向商店发送更多操作。
说我们正在使用带有 redux 的 mvvm 框架,每次商店分派一个动作,我都会将我的组件更新为
Store.subscribe(() => {
var { Order, Payment } = Store.getState():
this.order = Order;
this.payment = Payment;
this.setCountDown(Order.leftTime);
this.checkIsPaymentValid(Payment);
});
这里,setCountDown
&checkIsPaymentValid
只需要执行一次,以后就不会再调用了。结果,我目前正在向组件添加状态,它变得像旧的 jquery 方式,变成类似于下面的内容:
switch(Order.status) {
case ORDER_STATUS_NORMAL:
break;
case ORDER_HAS_SET_COUNTDOWN:
break;
}
对处理这种情况有什么建议吗?
我建议您在处理程序的末尾取消抄写。来自 redux docs:
To unsubscribe the change listener, invoke the function returned by subscribe.
因此,您可以拆分处理程序并始终更改 this.order
和 this.payment
,但只调用一次 setCountDown
和 checkIsPaymentValid
:
Store.subscribe(() => {
var { Order, Payment } = Store.getState():
this.order = Order;
this.payment = Payment;
});
const unsubscribe = Store.subscribe(() => {
var { Order, Payment } = Store.getState():
this.setCountDown(Order.leftTime);
this.checkIsPaymentValid(Payment);
unsubscribe();
});
如果您需要根据操作而不是当前状态执行某些逻辑,这通常表明它应该作为调度操作的一部分发生。换句话说,在 dispatch()
之前或之后而不是在更改处理程序中执行这些副作用。
如果此逻辑跨越多个组件,您可能需要考虑使用 Redux Saga 之类的东西,它可以让您定义长 运行 可以“采取”行动并执行某些方面的“sagas”效果或向商店发送更多操作。