为什么我的增量计数按钮返回 [Object object]

Why is my increment count button returning [Object object]

我正在尝试学习 React 钩子,并且正在尝试编写一个简单的函数来增加计数的状态。

import React, { useState } from "react";

export const HookCounter = () => {
    const [count, setCount] = useState(0);

    const incrementCount = (count) => {
        setCount(count + 1);
    };

    return (
        <div>
            <button onClick={incrementCount}>Press me!</button>
            <h1>
                You have pressed the button <strong>{count}</strong> times
            </h1>
        </div>
    );
};

但是,当我点击按钮时。而不是像我希望的那样计数器递增。我看到的是:

You have pressed the button [object Object]1 times.

这是为什么?

它无法正常工作的原因是因为您将计数定义为参数,它实际上是来自 onClick 的事件

函数不是从闭包中获取计数,而是从参数中获取计数,因为它优先。由于事件是一个对象,当您尝试执行 count + 1 时,它会将事件对象字符串化并向其添加 1,从而得到 [object Object]1

import React, { useState } from "react";

export const HookCounter = () => {
    const [count, setCount] = useState(0);

    const incrementCount = () => { // no count argument here
        setCount(count + 1);
    };

    return (
        <div>
            <button onClick={incrementCount}>Press me!</button>
            <h1>
                You have pressed the button <strong>{count}</strong> times
            </h1>
        </div>
    );
};

@Khatri 是对的,当您收到 count 作为参数时,它会获取该按钮的事件对象。你可以使用 console.log 打印计数(我将其重命名为事件)来检查它。

import React, { useState } from "react";

export const HookCounter = () => {
    const [count, setCount] = useState(0);

    const incrementCount = (event) => {
        console.log(event, 'event');
        setCount(count+1);
    };

    return (
        <div>
            <button onClick={incrementCount}>Press me!</button>
            <h1>
                You have pressed the button <strong>{count}</strong> times
            </h1>
        </div>
    );
};