在尝试使用react-redux实现删除功能时,我遇到了这个问题。
action / profile.js
export const deleteExperience = id => async dispatch => {
try {
const res = await axios.delete(`/api/profile/experience/${id}`);
dispatch({
type: UPDATE_PROFILE,
payload: res.data
});
dispatch(setAlert("Experience Removed", "success"));
} catch (err) {
dispatch({
type: PROFILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};
reducers / profile.js
case UPDATE_PROFILE:
return {
...state,
profile: payload,
loading: false
};
case PROFILE_ERROR:
return {
...state,
error: payload,
loading: false
};
答案 0 :(得分:0)
问题出在删除API中。 API应该像这样http://localhost:5000/api/profile/experience/5df8f54012b7a81ac04d6b25一样工作,但是在某种程度上,它也可以http://localhost:5000/api/profile/experience/5d与用户令牌一起工作。所以我从更改了api代码
try {
const profile = await Profile.findOne({ user: req.user.id })
const removeIndex = profile.education.map(item => item.id).indexOf(req.params.edu_id)
profile.education.splice(removeIndex, 1)
await profile.save()
res.json({ msg: 'Education Deleted'})
} catch (err) {
console.log(err.message)
res.status(500).send('Server Error')
}
到
try {
const foundProfile = await Profile.findOne({ user: req.user.id });
const eduIds = foundProfile.education.map(edu => edu._id.toString());
const removeIndex = eduIds.indexOf(req.params.edu_id);
if (removeIndex === -1) {
return res.status(500).json({ msg: "Server error" });
} else {
foundProfile.education.splice(removeIndex,1);
await foundProfile.save();
res.json({ msg: 'Education Deleted'})
}
} catch (error) {
console.error(error);
return res.status(500).json({ msg: "Server error" });
}
现在一切正常。