首页 > 解决方案 > 为什么我的增量计数按钮返回 [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.

为什么是这样?

标签: reactjsreact-hooksuse-state

解决方案


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

该函数不是从闭包中获取计数,而是从参数中获取它,因为它优先。由于 event 在您尝试执行时是一个对象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>
    );
};

推荐阅读