简体   繁体   English

redux-当一个资源依赖另一个时,如何适当地更新它们

[英]redux - when a resource depends on another, how to update them appropriately

Say I have a redux state tree like this: 假设我有一个redux状态树,如下所示:

{
  user: null,
  purchases: [],
}

The purchases belong to a user, so I always want to update the purchases when the user is updated (though purchases can be updated at other times, too). 购买属于用户,因此我总是想在更新用户时更新购买(尽管也可以在其他时间更新购买)。

How does one go about keeping the purchases up to date as the user changes? 随着用户的变化,如何使购买保持最新? I could perhaps dispatch an update of the purchases inside the action creator for the update to the user, but then I foresee adding dispatches to the fetchUser action creator every time I add a resource that depends on the current user, which seems redundant. 我也许可以在操作创建者内部调度购买的更新,以便将该更新发送给用户,但是我预见到每次添加依赖于当前用户的资源时,都会向fetchUser操作创建者添加调度,这似乎是多余的。

The code for my current action creators is below (note that I use thunk middleware): 我当前的动作创建者的代码如下(请注意,我使用thunk中间件):

Action creators for fetching the user : 用于获取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())
      );
    });
  }
};

Action creators for fetching the purchases : 动作创建者用于获取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()));
    });
  }
};

Your purchases reducer could be 'listening' to some specific user's actions type like fe FETCH_USER_SUCCESS and then updating that resource directly in there. 您的减少购买量功能可以“监听”某些特定用户的操作类型,例如fe FETCH_USER_SUCCESS,然后直接在其中更新该资源。

Sorry for my English. 对不起我的英语不好。

我认为您必须向用户传递购买详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM