【问题标题】:How To Update Redux State React Native如何更新 Redux 状态 React Native
【发布时间】:2021-03-21 15:34:29
【问题描述】:

我有一个像这样处于 redux 状态的对象。键实际上是问题 ID,值是答案 ID。

    userProgress: [
   {
    8: '2207',
    12: '28',
    38 : '42'   
    }
]

现在我想发送新的值,例如

dispatch(setUserProgress({
12: '2800'
}))

它应该找到该值并相应地更新,如果没有找到,它会将它添加到底部。

期望的结果:

  userProgress: [
   {
    8: '2207',
    12: '2800',
    38 : '42'   
    }
]

【问题讨论】:

  • 你在 redux 中使用了 switch case 吗?
  • 是的,我正在使用开关

标签: javascript reactjs react-native redux react-redux


【解决方案1】:

假设您的操作是{type:'the type',payload:{12:'2800'}},那么您可以执行以下操作:

return {...state, userProgress: {...state.userProgress,...payload}}

const reducer = (state, { type, payload }) => {
  if (type === 'the type') {
    return {
      ...state,
      userProgress: { ...state.userProgress, ...payload },
    };
  }
  return state;
};
console.log(
  'add new answer at the end',
  reducer(
    { userProgress: { a: 'a' } },
    { type: 'the type', payload: { newValue: 'newValue' } }
  )
);
console.log(
  'change existing value',
  reducer(
    { userProgress: { b: 'b' } },
    { type: 'the type', payload: { b: 'newValue' } }
  )
);

【讨论】:

  • 它返回错误,我们无法传播有效负载。我想找到对象中的现有值,然后更新它。如果没有找到,那么它将添加值
  • @UMAIRARSHAD 在拒绝之前,您应该对其进行测试。我添加了一个 sn-p 显示减速器工作。如果它对您不起作用,那么您的操作有问题,错误提示它,因为它抱怨 action.payload 无法传播。
猜你喜欢
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 2021-10-29
  • 2021-03-08
  • 2019-05-30
  • 1970-01-01
相关资源
最近更新 更多