在 redux 中更新嵌套状态
Update a nested state in redux
我在我的状态下有一个对象如下:
Exercise: {
id: 1,
question: '',
type: '',
Groups: [
{
id: 1,
category: {
id: 1,
value: 'xxx',
color: 'xxx'
},
groupParts: [
{
id: 1,
Index: 7
},
{
id: 2,
Index: 11
}
]
}
]
}
如何更新减速器中 id:2 中 Index 的值?
这是我最后一次尝试,它没有更新值,而是在当前状态下创建了另一个部分:
case CURRENT_WORD_INDEX_UPDATED:
const index=action.selectedWordIndex
return{...state,index:{...state.Groups[0].groupParts[1].index,index},}
您可以利用 immutability-helper 更新嵌套状态
import update from 'immutability-helper';
......
case CURRENT_WORD_INDEX_UPDATED:
const index=action.selectedWordIndex
return update(state, {
Groups: {
0: {
groupParts: {
0: {
Index: {
$set: index
}
}
}
}
}
})
我在我的状态下有一个对象如下:
Exercise: {
id: 1,
question: '',
type: '',
Groups: [
{
id: 1,
category: {
id: 1,
value: 'xxx',
color: 'xxx'
},
groupParts: [
{
id: 1,
Index: 7
},
{
id: 2,
Index: 11
}
]
}
]
}
如何更新减速器中 id:2 中 Index 的值?
这是我最后一次尝试,它没有更新值,而是在当前状态下创建了另一个部分:
case CURRENT_WORD_INDEX_UPDATED:
const index=action.selectedWordIndex
return{...state,index:{...state.Groups[0].groupParts[1].index,index},}
您可以利用 immutability-helper 更新嵌套状态
import update from 'immutability-helper';
......
case CURRENT_WORD_INDEX_UPDATED:
const index=action.selectedWordIndex
return update(state, {
Groups: {
0: {
groupParts: {
0: {
Index: {
$set: index
}
}
}
}
}
})