【发布时间】:2020-08-04 20:20:18
【问题描述】:
我正在使用 MERN 堆栈和 Redux。我发现很难创建用于更新 MongoDb 的 api 和操作。我有两个模型,我想通过 id 找到一个模型,然后用传入的另一个模型的对象更新它。这就是我的 api 和操作。谁能给我一些建议,告诉我如何完成这项工作以及如何将评论传递到 API 中?当我在 Postman 上测试它时,它说它已经工作了,但是当我在 url 中使用 id 时没有返回任何对象。我还将 res.json(subject) 更改为 res.send("Put req success") 但也没有显示此文本。请帮忙! :(
API
subjectRouter.put("/subject/:_id", (req, res) => {
Subject.findById(req.params._id, (err, subject) => {
if (err) {
res.send(err);
}
// what goes here to update the subject?
// the propery to be updated is 'comments'
// which is an array of comment objects
console.log(subject.json);
Subject.updateOne()
res.json(subject);
});
});
动作
export const updateSubject = () => (dispatch) => {
console.log("updateSubject called");
fetch("/api/subjects/Subject/:_id")
.then((res) => res.json())
.then((subject) =>
dispatch({
type: UPDATE_SUBJECT,
subjects: subject,
})
);
};
【问题讨论】:
-
能否在调用 updateSubject() 的地方添加代码?
-
它似乎是 api 接受
_id但你没有在fetch调用中传递它。 -
我认为处理API调用的“redux方式”是使用
thunks
标签: javascript reactjs redux react-redux mern