重新选择,我在哪里放置计算派生数据逻辑?

reselect, Where do I put the calculate derive data logic?

最近开始学习reselect,并尝试在我的项目中使用。

但是,我怀疑我应该把计算派生数据的代码放在哪里。

下面是我的代码片段,我想我把 formatDate calcDayLeftFromNow setDeriveData 逻辑放到我的 reducer 中也可以。

我在我的reducer中做派生数据计算也可以。

如果我这样做,似乎没有理由使用 reselect

function formatDate(millisecond) {
  let d = new Date(millisecond);
  let dateArr = [d.getFullYear(), d.getMonth() + 1, d.getDate()];
  let date = dateArr.join('.');
  return date;
}

function calcDayLeftFromNow(endTimeNum) {
  const timeDiff = endTimeNum - new Date().getTime();
  const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
  return daysDiff;
}

function setDeriveData(coupons) {
  return Object.values(coupons).map((coupon, index) => {
    coupon.startDate = formatDate(coupon.startTimeNum);
    coupon.endDate = formatDate(coupon.endTimeNum);
    coupon.dayLeft = calcDayLeftFromNow(coupon.endTimeNum);
    return coupon;
  });
}

const mapStateToProps = state => {
  const { coupons, current_tab, result, page } = state.yao_coupon;
  const newCoupons = setDeriveData(coupons);

  return {
    coupons: newCoupons,
    current_tab,
    result,
    page
  };
};

将选择器的代码放在 container component. Or if you don't want to split container from presentational 中很常见,只需将其放在组件中即可。

选择器的作用是从状态(存储)计算派生数据

而缩减器 指定应用程序的状态如何更改以响应操作

因此它们在您的应用中扮演着截然不同的角色。

Reselect readme 中,他们将所有内容都放在一个文件中,只是为了以最简单的方式展示其用途。

这是一个常见的文件夹结构,可以帮助您理解这一点:

| reducers #folder
    date.js
| components #folder
   | Clock #folder
     ClockContainer.js #contains mapStateToProps (and your selectors) and mapDispatchToProps
     Clock.js #the clock component

Some people 选择将选择器放在单独的文件中。但这取决于你的决定。例如,您可以将选择器放在容器组件中,只有在它变大时才将其移动到单独的文件中。将其移至单独文件的另一个原因是,如果您在整个应用程序的各个部分都需要相同的选择器。 (学分:@kwelch)

编辑

when I fetch bookList data from server, I calculate the derivedPrice in my FETCH_SUCCESS reducer

在您的 reducer 中计算派生价格将使其与 api 调用高度耦合,您将无法在其他地方使用分派的操作。 我的建议是将此计算移出减速器并在调度操作之前计算 derivedPrice