这也称为深度状态更新。我必须更新嵌套状态数组。
我正在实现一个简单的redux应用程序。这里我想更新嵌套数组对象的状态。我的reducer函数采用状态,动作。我必须使用新值更新状态的响应属性。我试图映射/迭代状态,但它不适合我。有没有办法更新这些特定的值并返回更新状态。
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;
}
}
initial 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
答案 0 :(得分:1)
我认为你的地图只是一个错误:
function hobbyReducer(state, action) {
switch(action.type) {
case "SUBMIT":
return {
...state,
answers: state.answers.map(answer => {
if (answer.text === action.text && answer.id === action.id) {
answer.response = answer.response + 1;
}
return answer;
});
}
default:
return state;
}
}