这是我需要更新的当前对象:
[
{ id: q1,
answers:[
{ id: a1,
answered: false
},
...
]
},
...
]
我无法弄清楚如何更新此对象并设置为例如answers = true。 有没有更好的方法来保存这种对象?我尝试使用React中的update插件但无法使其正常工作。
答案 0 :(得分:1)
您可以在reducer中以这种方式更新答案列表:
function update(state, action) {
// assuming you are passing an id of the item to be updated via action.itemId
let obj = state.whatever_list.filter(item => item.id === action.itemId)[0]
//assuming you are passing an id of the answer to be updated via action.answerId
//also, assuming action.payload contains {answered: true}
let answers = obj.answers.map(answer => answer.id === action.answerId ?
Object.assign({}, answer, action.payload) : answer)
obj = Object.assign({}, obj, {answers: answers})
return {
whatever_list: state.whatever_list.map(item => item.id == action.itemId? Object.assign({}, item, obj) : item)
}
}
以下是您的操作的样子:
function updateAnswer(itemId, answerId, payload) {
return {
type: UPDATE_ANSWER,
itemId: itemId,
answerId: answerId,
payload: payload
}
}
在您的react组件类中,假设有一个事件处理程序用于监视是否回答了问题:
export default class Whatever extends React.Component {
...
// assuming your props contains itemId and answerId
handleAnswered = (e) => {
this.props.dispatch(updateAnswer(this.props.itemId, this.props.answerId, {answered: true}))
}
...
}
所以基本上会发生这样的事情:
答案 1 :(得分:0)
您可以为答案键创建子缩减器。看看这个例子:
https://github.com/rackt/redux/blob/master/examples/async/reducers/index.js
答案 2 :(得分:0)
您可以使用dot-prop-immutable,更新将非常简单:
return dotProp.set(state, 'quiz.0.answers.0.answered', true);