[英]how to update state with reducer, when my state is an array not an object
[英]Sorting the array of object in reducer state
我想使用 redux 更新反應 state 但數據未正確排序
原始數組
"sections": [
{
"id": 8,
"user_id": 1,
"field_type_id": 8,
"section_id": 3,
"value": "+96******",
"type": "phone",
"url": "tel:",
"icon": "phone"
}
{
"id": 9,
"user_id": 1,
"field_type_id": 8,
"section_id": 3,
"value": "test@gmail.com",
"type": "email",
"url": "",
"icon": "email"
}
]
我正在使用此代碼更新 state。
state = { ...state,sections :[ ...state.sections.filter(
(section) => section.id !== action.payload.section.id
) , action.payload.section ] }
return state
更新數組對象后,正在反轉
"sections": [
{
"id": 9,
"user_id": 1,
"field_type_id": 8,
"section_id": 3,
"value": "test@gmail.com",
"type": "email",
"url": "",
"icon": "email"
}
{
"id": 8,
"user_id": 1,
"field_type_id": 8,
"section_id": 3,
"value": "+91344******",
"type": "phone",
"url": "tel:",
"icon": "phone"
}
]
我怎樣才能停止陣列反轉?
如果您只是想更新特定索引處的元素,那么只需使用Array.prototype.map
到 map 之前的數組到下一個,在到達時更新特定元素。 數組順序保持不變。
const nextState = {
...state,
sections: state.sections.map(
section => section.id === action.payload.section.id
? action.payload.section
: section
),
};
return nextState;
您可以使用以下 2 之一:
// filter const state = {...state, sections: state.sections.filter( (section) => section.id.== action.payload.section,id ); }. // Update const state = {..,state: sections. state.sections.map((section) => section.id.== action.payload?section.id. {.,:section: url, 'new Value' }; section ), };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.