在 redux 中更新嵌套状态 [英] Update a nested state in redux
本文介绍了在 redux 中更新嵌套状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的状态中有一个对象如下:
I have an object in my state as follows:
Exercise: {
id: 1,
question: '',
type: '',
Groups: [
{
id: 1,
category: {
id: 1,
value: 'xxx',
color: 'xxx'
},
groupParts: [
{
id: 1,
Index: 7
},
{
id: 2,
Index: 11
}
]
}
]
}
如何更新reducer中id:2中Index的值?
How can I update the value of the Index in id:2 in the reducer?
这是我最后一次尝试,它不更新值,而是在当前状态下创建另一个部分:
this is my last try which does not update the value, but creates another section in the current state:
case CURRENT_WORD_INDEX_UPDATED:
const index=action.selectedWordIndex
return{...state,index:{...state.Groups[0].groupParts[1].index,index},}
推荐答案
你可以使用 immutability-helper 更新嵌套状态
you can make use of immutability-helper to update a nested state
import update from 'immutability-helper';
......
case CURRENT_WORD_INDEX_UPDATED:
const index=action.selectedWordIndex
return update(state, {
Groups: {
0: {
groupParts: {
0: {
Index: {
$set: index
}
}
}
}
}
})
这篇关于在 redux 中更新嵌套状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文