簡體   English   中英

Axios 響應數據不與 useState 一起保存

[英]Axios response data is not saved with useState

在嘗試從我的快速后端和 MySQL 數據庫中獲取數據時,我的 React 前端使用 axios,但無法使用 useState 設置獲取的數據

我的前端功能看起來像這樣

const searchUser = () => {
    Axios.post("http://localhost:3001/searchUser", {
      username: username,
    }).then((response) => {
      if (response.data) {
        setResult(response.data);
      }
    });
  };

我的后端功能看起來像這樣

const searchUser = (req, res) => {
  const keyword = req.body.username;
  db.query(
    "SELECT id,username FROM users WHERE username like ?",
    "%" + keyword + "%",
    (err, result) => {
      if (err) {
        res.json({ message: err });
        console.log(err);
      } else {
        console.log(result);
        res.json({ result });
      }
    }
  );
};

我在使用 useState 鈎子保存數據時嘗試了很多方法,感謝您的幫助

在使用 Promises 然后而不是 async / await 時,請確保在獲取失敗時捕獲錯誤。

除非您與我們分享包含searchUser函數的整個組件以及您如何定義狀態,否則我無法指出您的錯誤。

我建議您做的是通過執行以下操作為您的提取添加一個捕獲:

const searchUser = () => {
    Axios.post("http://localhost:3001/searchUser", {
      username: username,
    }).then((response) => {
      if (response.data) {
        setResult(response.data);
      }
    }).catch((error) => {
      console.error(error);
    });
  };

如果您的請求發生任何異常,catch 會告訴您! 不要低估它的力量。

您可以查看的另一條路徑是控制台將您的輸出記錄在前端searchUser函數中,然后再將其設置為狀態。

我確實解決了這個問題,只是通過替換 res.json({ result }); 到 res.json(result); 在我的后端函數的最后一行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM