我正在尝试学习 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>
);
};
>@Khatri是正确的,当你收到count as参数时,它会获取该按钮的事件对象。您可以使用控制台.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>
);
};