You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件调用MongoDB查询时报TypeError类继承未定义问题求助

问题:React组件调用MongoDB查询方法时出现Class extends value undefined错误

我编写的FetchItemData.ts文件单独测试可正常连接MongoDB并获取数据,但在React的Category.tsx组件中调用查询方法时,出现如下错误:
client.ts:112 TypeError: Class extends value undefined is not a constructor or null

完整报错信息:

client.ts:112 TypeError: Class extends value undefined is not a constructor or null
    at node_modules/mongodb/lib/mongo_types.js (mongo_types.ts:402:74)
    at __require2 (chunk-TFWDKVI3.js?v=9e080f79:18:50)
    at node_modules/mongodb/lib/cursor/abstract_cursor.js (abstract_cursor.ts:16:1)
    at __require2 (chunk-TFWDKVI3.js?v=9e080f79:18:50)
    at node_modules/mongodb/lib/cursor/aggregation_cursor.js (aggregation_cursor.ts:11:1)
    at __require2 (chunk-TFWDKVI3.js?v=9e080f79:18:50)
    at node_modules/mongodb/lib/collection.js (collection.ts:6:1)
    at __require2 (chunk-TFWDKVI3.js?v=9e080f79:18:50)
    at node_modules/mongodb/lib/change_stream.js (change_stream.ts:4:1)
    at __require2 (chunk-TFWDKVI3.js?v=9e080f79:18:50)
warnFailedFetch @ client.ts:112
fetchUpdate @ client.ts:453
await in fetchUpdate (async)
(anonymous) @ client.ts:159
handleMessage @ client.ts:157
(anonymous) @ client.ts:90
Show 5 more frames
client.ts:114 [hmr] Failed to reload /src/components/Category.tsx. This could be due to syntax errors or importing non-existent modules. (see errors above)

已尝试的解决方法:

  • 更新依赖(问题反而更严重)
  • 使用dpdm检查循环依赖(未发现问题)
  • 将调用代码放入useEffect中(未解决)

当调用代码被注释时网站可正常启动,否则执行npm run dev会出现空白页。


相关文件

Category.tsx

import { useParams } from 'react-router-dom'
import Navbar from './Navbar';
import '../styles/category.css'
import { useContext, useEffect, useState} from 'react'
import { drawerContext } from '../utils/DrawerContext';
import { useSnapshot } from 'valtio/react';
import { store } from '../utils/store';
import ReactPaginate, { ReactPaginateProps }  from 'react-paginate'
import WestIcon from '@mui/icons-material/West';
import EastIcon from '@mui/icons-material/East';
import  {main}  from '../FetchItemData';


export const Category = () => {

    const {category} = useParams();
    const {gender} = useParams();
    
    const [currentPage, setCurrentPage] = useState(1);
    let lowerCategory = category!.toLowerCase();

    const {SearchBarContainerOpen, DrawerOpen, setIsSearchBarContainerOpen, setDrawerOpen } = useContext(drawerContext);
    console.log(lowerCategory)
    console.log(gender)
    
    const snapshot = useSnapshot(store);

    //useEffect(() => {
    //  main(gender!, category!);
    //})
   
    const products = [
      { id: 1, name: 'Product 1' },
      { id: 2, name: 'Product 2' },
      { id: 3, name: 'Product 3' },
      { id: 4, name: 'Product 4' },
      { id: 5, name: 'Product 5' },
      { id: 6, name: 'Product 6' },
      { id: 7, name: 'Product 1' },
      { id: 8, name: 'Product 2' },
      { id: 9, name: 'Product 3' },
      { id: 10, name: 'Product 4' },
      { id: 11, name: 'Product 5' },
      { id: 12, name: 'Product 6' },
      { id: 13, name: 'Product 6' },
      { id: 14, name: 'Product 6' },
    ];

    const handlePageChange: ReactPaginateProps['onPageChange'] = (selectedPage) => {
      setCurrentPage(selectedPage.selected);
    };

  
  return (
    <div className = "category-body">
      <Navbar iconColor='black' backgroundColor='white' z_index='1' />
      <main className = "main" style = {snapshot.SearchBar ? { filter: "blur(10px)" } : snapshot.DrawerOpen ? { filter: "blur(10px)" } : undefined}>
        <div className="grid-layout">
        {products.map((product) => (
          
          <div key={product.id} className="grid-item">
            <div className = "product-card">
              <div className = "product-card-image">
                <img src = "https://cdn.shopify.com/s/files/1/1003/3354/files/125SP232000F_ESSENTIALS_TEE_JET_BLACK_1_900x.jpg?v=1685911035">
                </img>
              </div>
              <div className = "product-card-item-description">
                <h3>Product Name</h3>
                <h4 className = "">Website</h4>
                <span>Price</span>
              </div>
            </div>
          </div>
         
        ))}
        </div>
        <div className = "pagination-container">
          <ReactPaginate 
            previousLabel={<WestIcon className = "icon"/>}
            nextLabel={<EastIcon className = "icon"/>} 
            pageCount={8}  
            breakLabel = {'...'}
            marginPagesDisplayed={3}
            previousClassName='previous' 
            nextClassName='next'
            pageClassName = 'page'
            containerClassName='pagination'
            onPageChange={handlePageChange}
            activeClassName='active'
            />
          </div>
      </main>
    </div>
  )
}

该组件需要根据gender和category参数从MongoDB获取数据进行渲染,但调用查询方法时出现上述错误。

FetchItemData.ts

import { MongoClient } from "mongodb";


export async function main(gender:string, category: string){
  /**
   * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
   */
  const uri = "mongodb+srv://(removed for this purpose)@cluster0.ww8cwxm.mongodb.net/?retryWrites=true&w=majority";


  const client = new MongoClient(uri);

  try {
      // Connect to the MongoDB cluster
      await client.connect();

      // Make the appropriate DB calls
      await  listDatabases(client, gender, category);

  } catch (e) {
      console.error(e);
  } finally {
      await client.close();
  }
}


export async function listDatabases(client: MongoClient, gender:string, category:string){
  let collection = gender == "Him" ? "him-items" : "her-items"
  let cursor = client.db("E-commerce").collection(collection).find({category: category}).limit(1)
  while (await cursor.hasNext()) {
    const document = await cursor.next();
    console.log(document);
  }

};

该文件用于从MongoDB获取数据,单独测试可正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:57:24