首页 > 解决方案 > 如何更新 Redux 状态 React Native

问题描述

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

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

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

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

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

期望的结果:

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

标签: javascriptreactjsreact-nativereduxreact-redux

解决方案


假设您的操作是,{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' } }
  )
);


推荐阅读