我如何正确使用过滤器和映射在reducers文件夹为锻炼对象?



我试图为锻炼对象做出正确的删除和更新请求,我得到一个错误,说过滤器不是一个函数,因为我在对象上使用它,而不是在数组上。下面是我用于reducer的代码。

import { FETCH_ALL, CREATE, UPDATE, DELETE, LIKE, COMMENT_WORKOUT } from '../constants/actionTypes';
export default (workouts=[],action)=>{
switch(action.type){
case FETCH_ALL:
return action.payload;
case CREATE:
return [...workouts, action.payload];
case UPDATE:
return workouts.map((workout) => (workout._id === action.payload._id ? action.payload : workout));
case LIKE:
return workouts.map((workout) => (workout._id === action.payload._id ? action.payload : workout));
case DELETE:
return workouts.filter((workout) => workout._id !== action.payload);
case COMMENT_WORKOUT:
return workouts.map((workout) => (workout._id === action.payload._id ? action.payload : workout));
default:
return workouts;
}
}

下面是我的actions文件夹的代码,其中包含了我发出的请求:

import { FETCH_ALL, CREATE, UPDATE, DELETE, LIKE, COMMENT_WORKOUT, COMMENT_MEAL } from '../constants/actionTypes';
import * as api from '../api';
export const getWorkouts=()=> async (dispatch)=>{
try{
const data=await api.fetchWorkouts();
dispatch({type:FETCH_ALL,payload:data});
console.log(data);
}catch(error){
console.log(error);
}
}
export const getWorkoutsBySearch=(searchQuery)=>async(dispatch)=>{
try{
const {data:{data}}=await api.fetchWorkoutsBySearch(searchQuery);
console.log(data);
}catch(error){
console.log(error);
}
}
export const createWorkout=(workout)=>async(dispatch)=>{
try{
const data=await api.createWorkout(workout);
dispatch({type:CREATE,payload:data});
console.log(data);
}catch(error){
console.log(error.message);
}
}
export const updateWorkout=(id,workout)=>async(dispatch)=>{
try{
const data=await api.updateWorkout(id,workout);
dispatch({type:UPDATE,payload:data})
}catch(error){
console.log(error);
}
}
export const deleteWorkout = (id) => async (dispatch) => {
try {
await api.deleteWorkout(id);

dispatch({ type: DELETE, payload: id });

} catch (error) {
console.log(error);
}
};
export const likeWorkout=(id)=>async(dispatch)=>{
try{
const data=await api.likeWorkout(id);
console.log(data)
dispatch({type:LIKE,payload:data})
}catch(error){
console.log(error);
}
}
export const postCommentOnWorkout=(data)=>async(dispatch)=>{
try{
const res=await api.postCommentOnWorkout(data);
dispatch({type:COMMENT_WORKOUT,payload:res})
}catch(error){
console.log(error);
}
}
export const postCommentOnMeal=(data)=>async(dispatch)=>{
try{
const res=await api.postCommentOnMeal(data);
dispatch({type:COMMENT_MEAL,payload:res})
}catch(error){
console.log(error);
}
}

我应该改变什么?地图函数也会得到与更新中相同的错误。谢谢!

因为你的action.payload是一个对象,当情况是'FETCH_ALL',你的状态成为一个对象,你不能使用数组方法。将对象转换为数组,然后返回。

export default (workouts = [], action) {
switch (action.type) {
case 'FETCH_ALL': {
const allWorkouts = []
const ids = Object.keys(action.payload)
for (let i = 0; i < ids.length; i++) {
allWorkouts.push(action.payload[ids[i]])
}
return allWorkouts 
}
}
}

相关内容

  • 没有找到相关文章

最新更新