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

React新冠疫情跟踪项目运行报Cannot call a class as a function错误如何解决

错误修复说明

根本原因

你的代码第3行导入逻辑错误:误将React组件react-countup作为类名拼接工具cx导入,你当前代码里的cx实际是CountUp类组件,在Grid组件上把它作为函数调用cx(styles.card, className)时,就会触发Cannot call a class as a function的类型错误。

修复步骤

  • 若未安装类名拼接依赖,先执行安装命令:npm install classnames 或 yarn add classnames
  • 修改导入语句,将原代码的第三行:
    import cx from 'react-countup';
    
    替换为:
    import cx from 'classnames';
    
  • 重启项目运行即可,报错会直接消失。

修正后的完整代码

import { Card, CardContent, Typography, Grid } from '@material-ui/core';
import CountUp from 'react-countup';
import cx from 'classnames';
import styles from './Cards.module.css';

const CardComponent = ({ className, cardTitle, value, lastUpdate, cardSubtitle }) => (
    <Grid item xs={12} md={3} component={Card} className={cx(styles.card, className)}>
      <CardContent>
        <Typography color="textSecondary" gutterBottom>
          {cardTitle}
        </Typography>
        <Typography variant="h5" component="h2">
          <CountUp start={0} end={value} duration={2.75} separator="," />
        </Typography>
        <Typography color="textSecondary">
          {new Date(lastUpdate).toDateString()}
        </Typography>
        <Typography variant="body2" component="p">
          {cardSubtitle}
        </Typography>
      </CardContent>
    </Grid>
  );

const Info = ({ data: { confirmed, recovered, deaths, lastUpdate } }) => {
  if (!confirmed) {
    return 'Loading...';
  }

  return (
    <div className={styles.container}>
        <Typography gutterBottom variant="h4" component="h2">Global</Typography>
      <Grid container spacing={3} justify="center">
        <CardComponent
          className={styles.infected}
          cardTitle="Infected"
          value={confirmed.value}
          lastUpdate={lastUpdate}
          cardSubtitle="Number of active cases from COVID-19."
        />
        <CardComponent
          className={styles.recovered}
          cardTitle="Recovered"
          value={recovered.value}
          lastUpdate={lastUpdate}
          cardSubtitle="Number of recoveries from COVID-19."
        />
        <CardComponent
          className={styles.deaths}
          cardTitle="Deaths"
          value={deaths.value}
          lastUpdate={lastUpdate}
          cardSubtitle="Number of deaths caused by COVID-19."
        />
      </Grid>
    </div>
  );
};

export default Info;

内容的提问来源于stack exchange,提问作者I.blue

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:36:02