reactjs - 为什么我的增量计数按钮返回 [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
.
为什么是这样?
解决方案
它无法正常工作的原因是因为您已将 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>
);
};
推荐阅读
- json - Typo3 v9 - Ajax 插件 JSON 响应为空
- php - file_get_contents():在 Apache2 中创建 SSL 上下文失败,但在 CLI 中有效
- python - 当我运行 cv.imshow 时,出现错误“QSocketNotifier:只能用于以 QThread 启动的线程”
- bash - 在 slurm 中提交依赖作业的问题
- vba - VBA 错误:对象不支持此操作(错误 445)
- python - 如何设置新索引
- java - Kubernetes nginx 入口未访问外部 API
- azure - Azure 管道中存储库的标记引用的通配符
- c++ - 是否可以使用 clang-format 使所有 if 语句成为一个块?
- python - 数据不是来自超类的子类初始化问题