Redux中的国家破坏问题

时间:2019-04-26 15:52:10

标签: reactjs redux react-redux

摘要

我正在重写redux状态,破坏子树,但是此后部分状态丢失了

项目信息

对我的React项目的依赖:

  • react-redux”:“ ^ 6.0.1”
  • redux”:“ 4.0.1”
  • redux-thunk”:“ 2.3.0”
  • ...

CODE

初始状态:

const initialState = {
  fetching: false,
  data: {
    events: null,
    issues: null,
    sla: {
      daily: null,
      weekly: null,
    },
    lastUpdate: null,
  },
  error: null,
};

减速器中缺少数据的部分:

case types.FETCH_DATA.SUCCESS:
  return {
    ...state,
    data: {
      ...state.data,
      sla: {
        ...state.data.sla,
        ...payload.data.sla,
      },
      ...payload.data,
    },
    fetching: false,
    error: null,
  };

按操作发送数据:

{
  events: ["event 1", "event 2"],
  issues: ["issue 1", "issue 2"],
  sla: {
    daily: ["daily 1", "daily 2"],
}

动作分派后的状态:

{
  fetching: false,
  data: {
    events: ["event 1", "event 2"],
    issues: ["issue 1", "issue 2"],
    sla: {
      daily: ["daily 1", "daily 2"],
    },
    lastUpdate: null,
  },
  error: null,
}
  

data.sla.weekly丢失

如果我不发送有关行动的问题,则

{
  events: ["event 1", "event 2"],
  sla: {
    daily: ["daily 1", "daily 2"],
}

动作分派后的状态:

{
  fetching: false,
  data: {
    events: ["event 1", "event 2"],
    issues: null,
    sla: {
      daily: ["daily 1", "daily 2"],
    },
    lastUpdate: null,
  },
  error: null,
}
  

在这种情况下... state.data解构工作正常,但是... state.data.sla无效

请有人帮助我!

1 个答案:

答案 0 :(得分:1)

解构工作按预期进行,但顺序应更改

case types.FETCH_DATA.SUCCESS:
  return {
    ...state,
    data: {
      ...state.data,
      sla: {
        ...state.data.sla,
        ...payload.data.sla,
      },
      ...payload.data, <---- This is overriding the previous `sla` but the action contains `sla.daily` only, that's why your `sla.weekly` is gone
    },
    fetching: false,
    error: null,
  };

尝试更改顺序

case types.FETCH_DATA.SUCCESS:
  return {
    ...state,
    data: {
      ...state.data,
      ...payload.data, <-- Move up before `sla`
      sla: {
        ...state.data.sla,
        ...payload.data.sla,
      },
    },
    fetching: false,
    error: null,
  };

但是您的状态似乎相当复杂,如果可能的话,简化它可以使您的生活更轻松...