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

React计数器点击按钮后消失或显示NaN的问题求助

问题分析与修复方案

核心问题

  1. 函数组件误用this:你写的是React函数组件,不存在类组件的实例对象,this在这里指向undefined,所以this.count会得到undefined,和数字运算后直接变成NaN。
  2. 状态更新覆盖错误:你的counts是包含count1和count2的对象,但调用setCounts时直接传入了count+1这类数值,这会把整个counts对象替换成单个数字,后续渲染时counts.count1和counts.count2找不到对应属性,自然计数器就消失了。

修复后的代码

import { useState } from 'react';

export default function Counter() {
  const [counts, setCounts] = useState({ count1: 0, count2: 0 });

  const increment = (key) => {
    // 用展开运算符保留原有状态,仅更新目标计数器
    setCounts({ ...counts, [key]: counts[key] + 1 });
    // 若更新依赖最新状态,更稳妥的函数式更新写法:
    // setCounts(prevCounts => ({ ...prevCounts, [key]: prevCounts[key] + 1 }));
  };

  const decrement = (key) => {
    setCounts({ ...counts, [key]: counts[key] - 1 });
    // 函数式更新版本:
    // setCounts(prevCounts => ({ ...prevCounts, [key]: prevCounts[key] - 1 }));
  };

  return (
    <div>
      <h1>{counts.count1}</h1>
      <h1>{counts.count2}</h1>
      <button onClick={() => increment('count1')}>Increment 1</button>
      <button onClick={() => decrement('count1')}>Decrement 1</button>
      <button onClick={() => increment('count2')}>Increment 2</button>
      <button onClick={() => decrement('count2')}>Decrement 2</button>
    </div>
  );
}

关键修改说明

  • 把增减函数的参数从具体数值改成要操作的键名(count1/count2),明确指定要更新的计数器。
  • 更新状态时使用{ ...counts, [key]: 新值 }:展开运算符...counts会保留原对象的所有属性,再通过动态键[key]修改目标计数器的数值,不会丢失其他计数器的状态。
  • 推荐使用注释里的函数式更新写法,当状态更新依赖于前一次状态时,这种方式能确保拿到最新的状态值,避免闭包导致的状态过期问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:57:11