简体   繁体   English

Axios 响应数据不与 useState 一起保存

[英]Axios response data is not saved with useState

While trying to fetch data from my express backend and MySQL database, with my react frontend using axios, it fails to set the fetched data using useState在尝试从我的快速后端和 MySQL 数据库中获取数据时,我的 React 前端使用 axios,但无法使用 useState 设置获取的数据

my frontend function looks like this我的前端功能看起来像这样

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

and my backend function looks like this我的后端功能看起来像这样

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 });
      }
    }
  );
};

I tried many methods while saving the data with the useState hook, I appreciate any help我在使用 useState 钩子保存数据时尝试了很多方法,感谢您的帮助

While using Promises and then instead of async / await make sure to catch the errors if your fetch fails.在使用 Promises 然后而不是 async / await 时,请确保在获取失败时捕获错误。

Unless you share with us the whole component that contains the searchUser function and how you defined the state i cannot pin point you on the error.除非您与我们分享包含searchUser函数的整个组件以及您如何定义状态,否则我无法指出您的错误。

What i suggest you to do is adding a catch to your fetch by doing the following:我建议您做的是通过执行以下操作为您的提取添加一个捕获:

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

If any abnormalities has happened in your request the catch will tell you!如果您的请求发生任何异常,catch 会告诉您! Don't underestimate it's power.不要低估它的力量。

Another path you can look into is console logging your output in front end searchUser function just before setting it in the state.您可以查看的另一条路径是控制台将您的输出记录在前端searchUser函数中,然后再将其设置为状态。

I did solve the problem, just by replacing res.json({ result });我确实解决了这个问题,只是通过替换 res.json({ result }); to res.json(result);到 res.json(result); in the last line in my backend function在我的后端函数的最后一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM