javascript - 如何更新 Redux 状态 React Native
问题描述
我有一个像这样处于 redux 状态的对象。键实际上是问题 ID,值是答案 ID。
userProgress: [
{
8: '2207',
12: '28',
38 : '42'
}
]
现在我想发送新的值,比如
dispatch(setUserProgress({
12: '2800'
}))
它应该找到该值并相应地更新,如果没有找到,它将在底部添加它。
期望的结果:
userProgress: [
{
8: '2207',
12: '2800',
38 : '42'
}
]
解决方案
假设您的操作是,{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' } }
)
);
推荐阅读
- java - 使用 Java FileSystem 抢救临时 zip 文件
- cron - 从早上 8 点到晚上 7:30 每分钟运行一次的作业的 Cron 计划
- c# - 使用 Office Interop 导出 Excel 工作表时出现问题
- html - 如何在手机视图的右上角显示社交媒体图标?
- php - 使用内部连接选择 COUNT
- android - 无法解析 com.android.tools.build:gradle:3.3.0-alpha06
- jboss - org.xml.sax.SAXException:[...] 中的元素无效
- hadoop - 在 hive 的分区级别添加列
- android - 安卓模拟器老是说过时
- javascript - 谷歌表单输入字段中的 Keydown 事件