我正在尝试从redux商店中删除一个项目。当我从UI中删除该项时,我收到错误"无法读取未定义的属性CourseId"。当我尝试使用过滤器删除项目时,错误来自reducer的DELETE_COURSE_SUCCESS操作。
这是我的API
static deleteCourse(course) {
if (course.CourseId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
let url = '/api/courses/delete/' + course.CourseId;
fetch(url, {
method: 'post',
dataType: 'json',
credentials: 'include',
contentType: "application/json",
headers : {
'Accept':'application/json',
'Content-Type': 'application/json'
}
}).then((response) => {
if (response.ok === true)
return response;
}).catch(function(err) {
alert('Error: ' + err);
});
resolve(course);
}, delay);
});
}
}
我的行动:
export function deleteCourseSuccess(course) {
return { type: types.DELETE_COURSE_SUCCESS, course };
}
export function deleteCourse(course) {
return function(courseDispatch, getState) {
courseDispatch(beginAjaxCall());
return courseApi.deleteCourse(course).then(deletedCourse => {
courseDispatch(deleteCourseSuccess(deletedCourse));
}).catch(error => {
courseDispatch(ajaxCallError(error));
throw(error);
});
};
}
这是我的减速机:
export default function courseReducer(state = initialState.courses, action) {
switch(action.type) {
case types.LOAD_COURSES_SUCCESS:
return action.courses;
case types.CREATE_COURSE_SUCCESS:
return [
...state,
Object.assign({}, action.course)
];
case types.UPDATE_COURSE_SUCCESS:
return [
...state.filter(course => course.CourseId !== action.course.CourseId),
Object.assign({}, action.course)
];
case types.DELETE_COURSE_SUCCESS:
return [
// this is where the error occurs, says that course is undefined
...state.filter(course => course.CourseId !== action.course.CourseId)
];
default:
return state;
}
}
以下是组件中的delete方法:
deleteCourse(event) {
event.preventDefault();
this.setState({deleting: true});
this.props.actions.deleteCourse(this.state.course)
.then(() => this.redirect())
.catch(error => {
toastr.error('deleteCourse:' + error);
this.setState({deleting: false});
});
}
如果我只是在DELETE_COURSE_SUCCESS操作类型中返回...状态,我没有收到错误,但删除的项目仍然处于状态。我知道该项目也在那里因为我在return语句之前放了以下警告并在那里看到它:
alert(JSON.stringify(state.filter(course => course.CourseId === action.course.CourseId)));
这可能是我想念的简单事情,但对于我的生活,我无法弄清楚。
编辑:我找到了罪魁祸首。在我要删除项目的组件中,我有以下内容:
componentWillReceiveProps(nextProps) {
if (this.props.course.CourseId != nextProps.course.CourseId) {
// necessary to populate form when existing course is loaded directly
this.setState({course: Object.assign({}, nextProps.course)});
}
}
当我评论这个时,错误就消失了。这是" nextProps.course"这是未定义的。猜猜我更好地阅读了反应组件生命周期,而不是盲目地复制和粘贴代码:(