![](/img/trans.png)
[英]How to update a variable that depends on another variable in a function?
[英]redux - when a resource depends on another, how to update them appropriately
假設我有一個redux狀態樹,如下所示:
{
user: null,
purchases: [],
}
購買屬於用戶,因此我總是想在更新用戶時更新購買(盡管也可以在其他時間更新購買)。
隨着用戶的變化,如何使購買保持最新? 我也許可以在操作創建者內部調度購買的更新,以便將該更新發送給用戶,但是我預見到每次添加依賴於當前用戶的資源時,都會向fetchUser操作創建者添加調度,這似乎是多余的。
我當前的動作創建者的代碼如下(請注意,我使用thunk中間件):
用於獲取user
操作創建者:
export const fetchUserSuccess = user => ({
type: FETCH_USER_SUCCESS,
user,
});
export const fetchUserFailure = () => ({
type: FETCH_USER_FAILURE,
});
export const fetchUser = () => {
return dispatch => {
return getLoggedInUser(resp => {
const { user } = resp;
return (
user
? dispatch(fetchUserSuccess(user))
: dispatch(fetchUserFailure())
);
});
}
};
動作創建者用於獲取purchases
:
export const fetchPurchasesSuccess = purchases => ({
type: FETCH_PURCHASES_SUCCESS,
purchases,
});
export const fetchPurchasesFailure = () => ({
type: FETCH_PURCHASES_FAILURE,
});
export const fetchPurchases = user => {
return dispatch => {
return getPurchases(user, resp => {
const { purchases } = resp;
return (
purchases
? dispatch(fetchPurchasesSuccess(purchases))
: dispatch(fetchPurchasesFailure()));
});
}
};
您的減少購買量功能可以“監聽”某些特定用戶的操作類型,例如fe FETCH_USER_SUCCESS,然后直接在其中更新該資源。
對不起我的英語不好。
我認為您必須向用戶傳遞購買詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.