【问题标题】:Creating a put api request using Redux使用 Redux 创建 put api 请求
【发布时间】: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


【解决方案1】:

似乎 api 将 _id 作为参数,但您没有在 fetch 调用中传递它,这里试试这个:

export const updateSubject = (id) => (dispatch) => {
  console.log("updateSubject called");
  fetch(`/api/subjects/Subject/${id}`)
    .then((res) => res.json())
    .then((subject) =>
      dispatch({
        type: UPDATE_SUBJECT,
        subjects: subject,
      })
    );
};

【讨论】:

  • 谢谢,你知道我将如何更新返回的主题吗?所以我需要添加到 Subject.updateOne()
  • 你想在后端更新哪里??使用猫鼬 findByIdAndUpdate() .
猜你喜欢
  • 2018-05-31
  • 2019-09-23
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-29
  • 2011-08-30
相关资源
最近更新 更多