reactjs – 处理redux-saga或reducer中下载的项目规范化?

我从remove API获得的数据不是我的应用程序可以处理的格式.

我的传奇下载数据.

谁应该处理正常化?

在使用规范化数据调度成功动作之前的传奇本身?

或者路由器是否应该在构建新状态之前规范化日期?

编辑我选择在传奇中规范化并保持减速器清洁.它只是用新的活动替换了活动.更新了它.

减速机

export default function account(state = ACCOUNT, action) {
  switch (action.type) {
    case "account/LOGIN_SUCCESS":
      const { access_token, user } = action
      return { ...state, user, access_token, authenticated: true, error: "" }
    case "account/LOGOUT_SUCCESS":
      return ACCOUNT
    case "account/LOGIN_ERROR":
      return { ...state, error: action.error }
    case "account/ACTIVITIES_UPDATED":
      return { ...state, activities: action.activities }
    default:
      return state
  }
}

这些是传奇:

function sortActivities(activities) {
  return action.activities.sort((a,b) => b.timestamp.localeCompare(a.timestamp))
}

function addInvoices(activities) {
  let lastYearMonth, invoiceItem
  return activities.reduce((state, item, index) => {
    const currentYearMonth = item.timestamp.substr(0,7)
    if (currentYearMonth != lastYearMonth) {
      lastYearMonth = currentYearMonth
      invoiceItem = {
        id: currentYearMonth,
        type: "invoice",
        parking: 0,
        rebates: 0,
        sum: 0,
        timestamp: currentYearMonth
      }
      state.push(invoiceItem)
    }
    const amount = Math.abs(Number(item.gross_amount))
    if (item.type == "parking") {
      invoiceItem.parking += amount
      invoiceItem.sum -= amount
    } else if (item.type == "rebate" || item.type == "surplus") {
      invoiceItem.rebates += amount
      invoiceItem.sum += amount
    }
    state.push(item)
    return state
  }, [])
}

function *getActivities(access_token) {
  console.info("fetch activities")
  try {
    const activities = yield call(getActivitiesAsync, access_token)
    console.info("activities fetched")
    yield put(activitiesUpdated(addInvoices(activities.sortActivities(activities))))
  } catch (error) {
  }
}

function *updateActivities() {
  while (true) {
    const { access_token } = yield take(LOGIN_SUCCESS)
    console.info("Calling getActivities")
    yield call(getActivities, access_token)
    while (true) {
      const {type } = yield take([REFRESH_ACTIVITIES, LOGOUT])
      if (type == LOGOUT) {
        break
      }
      yield call(getActivities, access_token)
    }
  }
}

当你想到updateActivities传奇中的双重包裹while循环时?

也是正确的

产量([REFRESH_ACTIVITIES,LOGOUT])

只是一个捷径

屈服竞赛[take(REFRESH_ACTIVITIES),take(LOGOUT)]

最佳答案 在这种情况下,你最终可以自由地为你做任何事情 – 对于一个而言,没有一个强有力的理由.你最终可能会发现,根据数据的结构,在saga中执行它会产生更少的代码,因为你只需要将结果分成两次(两个减少器中的每一个都关注数据.但是这可能是也可能不是这种情况.我也喜欢在减速器中这样做的想法,因为减速器通常应该尽可能简单,并且这个模型适合这种情况.

但就像我说的那样,我认为对于一方而言,并没有一个强烈的普遍论证.

点赞