我试图通过运行filter和map方法来改变状态,当我返回数组时,状态变得不确定。
const getAllApprovedProviderReducer = (state=defaultState, action) => {
if(action.type === GET_ALL_APPROVED_PROVIDER) {
return {
...state
}
}
if(action.type === FILTER_BY_FINANCIAL_SERVICES) {
console.log(action.payload)
return {
...state,
success: state.success.map((item, index)=> {
item.servicesOffered.filter(i=>{
if(i===action.payload) {
return item
}
else {
// console.log(state.success);
return item
}
})
})
}
}
return state;
}
在表示组件上,状态更改为未定义。 我做错了,使状态不确定。
答案 0 :(得分:1)
根据我的评论:
您传递给.map
的函数不会返回任何内容,因此每个值都映射到undefined
。 return
不会跨越函数边界,您传递给.filter
的函数应返回布尔值。
如果只想保留提供特定服务的对象,则可以通过以下方式进行操作:
state.success.filter(item => item.servicesOffered.includes(action.payload))
.filter
将删除回调返回false
的每个元素。
在这里使用.map
是没有意义的,因为它始终是输入与输出之间的1:1映射。如果要减少元素数量,则必须使用.filter
。
虽然可以使用.filter
来测试数组中某个值的存在,但还有更具体的方法,例如.includes
和.some
。