You need to enable JavaScript to run this app. 使用Node.js Express关联game与users表并在React端展示的实现求助
优惠活动
大模型
产品
解决方案
定价
更多

使用Node.js Express关联game与users表并在React端展示的实现求助

代码问题修正

后端接口调整点

  • 消除同名字段覆盖问题:原SQL语句SELECT game.*, users.* 会让两表共有的同名字段(如game_code)在返回结果中被后查询的users表同名字段覆盖,需为重复字段显式指定别名,保证前端能拿到对应表的正确值。
  • 补全异常响应逻辑:当前数据库查询报错时仅在服务端控制台打印日志,未给前端返回对应状态,会导致前端请求长期挂起。

调整后的接口代码:

app.get("/af", async (req, res) => {
  try {
    const queryResult = await pool.query(
      `SELECT 
        game.game_code,
        game.game_location,
        users.user_code
       FROM users 
       INNER JOIN game ON users.game_code = game.game_code`
    );
    res.json(queryResult.rows);
  } catch (err) {
    console.error(err.message);
    res.status(500).json({ msg: "关联查询执行失败" });
  }
});

前端组件调整点

  • 补全依赖导入:useState、useEffect、Fragment 均为React导出的API,未显式引入会直接触发编译报错。
  • 修复JSX结构缺失问题:原代码中Fragment闭合标签、map渲染的<tr>标签均未正确闭合,会导致React渲染逻辑中断。
  • 修正字段绑定错误:原代码中表格表头声明了user_code列,实际渲染绑定的是game_location;行key属性绑定的game.game为不存在的字段,会触发React的key警告。

调整后的组件代码:

import React, { Fragment, useState, useEffect } from "react";

const List = () => {
  const [af, setAF] = useState([]);

  const getTodos = async () => {
    try {
      const response = await fetch("http://localhost:5000/af");
      const jsonData = await response.json();
      setAF(jsonData);
    } catch (err) {
      console.error(err.message);
    }
  };

  useEffect(() => {
    getTodos();
  }, []);

  return (
    <Fragment>
      <table className="table mt-5 text-center">
        <thead>
          <tr>
            <th>game_code</th>
            <th>game_location</th>
            <th>user_code</th>
          </tr>
        </thead>
        <tbody>
          {af.map(item => (
            <tr key={`${item.game_code}_${item.user_code}`}>
              <td>{item.game_code}</td>
              <td>{item.game_location}</td>
              <td>{item.user_code}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Fragment>
  );
};

export default List;

内容的提问来源于stack exchange,提问作者Aperis122

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 21:36:04