[英]How To Update Redux State React Native
我在 redux state 中有一个 object 像这样。 键实际上是问题 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' } } ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.