使用React-Redux-Thunk ... 我试图了解在我的reducer中处理此用例的最佳方法。在数据库中插入新的searchterm时,我需要更新状态(这是热门搜索的json摘要(键“ value- searchterm:count)。如果我的serachterm键存在,则我的目标是将1加到计数中,否则创建一个新的键:带有“ serachterm”的值:1
我如何在我的reducer中编写代码
export default function topSearchReducer(state = {topSearches: []}, action) {
console.log('action', action);
console.log('Inside Top Search reducer state', state);
switch (action.type) {
case 'FETCH_TOP_SEARCHES':
return {topSearches: action.payload}
case 'UPDATE_TOP_SEARCH'
if(action.searchterm in state.topSearches[0]){
console.log( 'FOUND IN OBJECT!');
}
default:
return state
}
};
答案 0 :(得分:1)
据我所理解,topSearches数组的每个项目都是一个对象-映射,键为searchTerm
,值为count
。我不了解您在数组中的内容,因为您仅检查数组的第一项(topsearches[0]
),但是好的,请尝试以下操作:
case 'UPDATE_TOP_SEARCH':
return {
...state,
topSearches: [
// update first item of array
{
// copy the previous state of map
...state.topSearches[0],
// update item of map -
// if searchterm was already there increase the count, otherwise add value 1
[action.searchterm]: (
action.searchterm in state.topSearches[0] ?
state.topSearches[0][action.searchterm] + 1 :
1
)
},
// just put shallow copy of all other items
...state.topSearches.slice(1)
]
}