【发布时间】:2017-10-12 03:12:06
【问题描述】:
这也称为深度状态更新。我必须更新嵌套状态数组。
我正在实现一个简单的 redux 应用程序。在这里,我想更新嵌套对象数组的状态。我的减速器功能需要状态,动作。我必须用新值更新状态的响应属性。我试图映射/迭代状态,但它不适合我。有没有办法更新这些特定值并返回更新状态。
const sampleData = [{
"id": 1,
"text": "Hobby",
"answers": [{
"id": 1,
"text": "Chess",
"responses": 5
}]
}];
const action = {
type: "VOTE",
questionId: 1,
answerId: 3
};
这是我在表单上单击提交按钮时调用的 handleSubmit 函数。
handleSubmit(e){
const store = createStore(hobbyReducer, hobby); // created store here
var k = (document.querySelector('input[name = "hobby"]:checked').value);
store.dispatch({type:"SUBMIT", text: k, id: 1}); // Dispatching action to reducer
store.subscribe(()=>{
console.log(store.getState());
});
}
这是程序的reducer部分:
function hobbyReducer(state, action) {
switch(action.type){
case "SUBMIT":
return{
...state,
answers: state.answers.map(e=> (e.text === action.text && e.answers.id === action.id)?
{ ...answers,
responses: (e.responses+1)} :
hobby )
}
break;
default:
return state;
}
}
初始状态 = sampleData; // 上面给出的数组对象
我无法更新嵌套数组中的响应属性
这是我想写的代码,经过一番研究,我终于做到了。虽然这不是时间复杂度的解决方案。
`
case "SUBMIT":
const updatedState = state.map(e =>{
if(e.id === action.id)
return{...e,
answers: e.answers.map(f =>{
if(f.text === action.text){
return{
...f,
...{responses: f.responses + 1},
}
}
return f;
})
}
return e;
})
console.log("updatedstate", updatedState)
return updatedState
【问题讨论】:
-
请提供状态的上一个和下一个值,您正在使用的reducer以及用于状态转换的操作。
-
@palsrealm 请检查我是否更新了信息