在reducer内使用Date.now()进行替换

时间:2018-08-15 23:24:42

标签: javascript reactjs redux

文档说我应该通过在reducers中使用新的Date等来避免状态突变。请给我一些建议,应该如何做。

操作:

const RECEIVE_PRICES = 'RECEIVE_PRICES';

function receivePrices(prices) {
  return {
    type: RECEIVE_PRICES,
    receivedAt: Date.now(),
    prices,
  };
}

减速机:

 ...
 case RECEIVE_PRICES: {
      let { prices } = action;

      prices = prices.map((p) => {
        const baseQuote = p.symbol.split('/');
        return { ...p, baseCurrency: baseQuote[0], quoteCurrency: baseQuote[1] };
      });

      prices.sort(
        (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
      );

      return {
        ...state,
        prices,
        pricesLoading: false,
        pricesError: null,
      };
    }
    default:
      return state;
  }

1 个答案:

答案 0 :(得分:1)

在Redux中,所有副作用(不仅是api调用)都应在Action Creators中进行。您应该将此逻辑移到动作创建器中,并让调用者传递必要的参数。