【问题标题】:Axios Post is not completing every timeAxios Post 并非每次都完成
【发布时间】:2021-12-02 21:16:07
【问题描述】:

我是 React 新手,遇到了一些问题。

这是我当前的 API 调用。

Axios.post(Addr_currentRound_addOne, { gameId: gameId }).then(history.push("/leiter_tunierplan/"+gameId));

这是对应的API Code sn-p。

app.post("/currentRoundAddOne", (req, res) => {

  
  const gameId = req.body.gameId;
    
  db.query(
    "UPDATE tunierplan SET currentRound=currentRound+1 WHERE id=?;",
    [gameId],
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        res.send("Daten Übertragen");
      }
    }
  );
});

这里的问题: currentRound,应该总是在调用执行时增加 +1。 然后重定向到给定的“/leiter_tunierplan/” 但 有时,它不起作用。它不会增加任何值(+1) 我的第一个想法是:因为它是异步的,所以在它完成之前我会从 history.push 中取消它。我对吗?我该如何解决它。 已经谢谢了。

【问题讨论】:

  • 但是你的代码gameId 没有任何地方增加?
  • “因为它是异步的,所以在它完成之前我会从 history.push 中取消它。我说的对吗?” - 不,因为你使用的是 then Promise,这从一开始就排除了异步 - 历史推送只会在对您的请求的响应到达时发生。
  • gameId 不相关。 @Jer
  • 你在抱怨它没有被增加。您的代码中没有任何内容显示它正在递增。
  • 那么:那我该如何解决呢?因为它应该只在 Axios.post 完成时重定向。

标签: javascript mysql node.js reactjs express


【解决方案1】:

游戏gameId 是否已经为下一页增加了id?我没有看到它在您的代码中的任何地方增加。

如果是这样,请尝试将 history.push 放入回调中,如下所示:

...then(() => history.push("/leiter_tunierplan/"+gameId));

这是因为then将回调函数作为参数

【讨论】:

  • 这里可能有点混乱。 gameId 是一个不会改变整个游戏的 ID。它只是在那里确定您当前所在的游戏。该游戏有多个回合。并且 currentRound 应该在数据库中增加,依赖于 GameId。
  • 我刚刚尝试了您的解决方案,但它不起作用。我将不胜感激任何其他解决方案,首先执行 API 调用,然后执行历史推送。谢谢
【解决方案2】:

所有的解决方案是添加preventDefault(); 我的问题是,边重新加载了..

【讨论】:

    【解决方案3】:

    我认为您可以尝试async-await,因为对数据库的请求是基于承诺的。 我的建议:

    app.post("/currentRoundAddOne", async (req, res) => {
        const gameId = req.body.gameId
        const data = await db.query("UPDATE tunierplan SET currentRound=currentRound+1 WHERE id=?;", [gameId],
        (err, result) => {
              if (err) console.log(err);
        }
        console.log(data) // check updated data, it should return id
    })
    

    我希望它有效!

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 2012-07-13
      • 2014-01-05
      • 2021-12-14
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多