reactjs 如何通过ID获取数据以显示在客户端- react

xqkwcwgp  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(138)

在我的服务器上

/* GET event listing by ID */
router.get('/:keyInfo_id', async function (req, res, next) {
  let { keyInfo_id } = req.params;

  try {
    let result = await db(`SELECT activities.keyInfo_id, date, title, deadline, activities_id, activityName, description, price, location FROM activities INNER JOIN keyInfo ON keyInfo.keyInfo_id = activities.keyInfo_id WHERE keyInfo.keyInfo_id = ${keyInfo_id} `);

    let event = result.data;
    if (event.length !== 0) {
      res.send(event);
    } else {
      // event array is empty... no event found
      res.status(404).send({ error: 'Event not found' });
    }
  }catch (err) {
    res.status(500).send({error: err.message});
  }
});

在我的客户端-React

function App() {
  let [allEvents, setAllEvents] = useState([]);

  // useEffect() will call getEvent() when App is mounted on the DOM
  useEffect(() => {
    getEvent();  
  }, []);
  // the empty [] means only call it once

  //Get all the events
  async function getEvent() {
    try {
      let response = await fetch('/event');
      if (response.ok) {
        let data = await response.json();
        setAllEvents(data);
      } else {
        console.log(`Server error: ${response.status}: ${response.statusText}`);
      }
    } catch(err) {
      console.log(`Network error: ${err.message}`);
    }
  }

  // Get all the events by ID
  async function getEvent(id) {
    try {
      let response = await fetch('/:keyInfo_id');
      if (response.ok || response === id ) {
        let data = await response.json();
        setAllEvents(data);
      } else {
        console.log(`Server error: ${response.status}: ${response.statusText}`);
      }
    } catch(err) {
      console.log(`Network error: ${err.message}`);
    }
  }

我正在尝试获取sql表中某个事件的数据。因此,当我更改客户端URL http://localhost:3000/dashboard/和add /:keyInfo_id时,我只能在页面上看到我想要的事件的数据,而不是所有数据。
此刻,如果我做http://localhost:3000/dashboard/3(3是在mysql上生成的事件的id),我的页面是空白的,不会显示任何东西。我不明白为什么

lxkprmvk

lxkprmvk1#

getEvent函数名被使用了两次。还添加了一个视图来显示allEvents中的数据。
尝试console.log(allEvents);以确定是否正确提取了数据。

相关问题