javascript - Why can't the dispatch function of a useState hook be passed directly into an onClick handler?
问题描述
const Counter = () => {
const [count, setCount] = useState(0);
// return <button onClick={setCount(count + 1)}>{count}</button>;
return <button onClick={() => setCount(count + 1)}>{count}</button>;
};
I'm aware that the commented out line causes an infinite loop but I want to know why that's the case. Isn't the setCount
dispatch function invoked only on click?
解决方案
It's because the expression within a {}
in JSX is evaluated and then its result is used where that {}
was — in this case, as the value of the onClick
property. So onClick={setCount(count + 1)}
evaluates setCount(count + 1)
(calling the function, which will set the state) and then uses the resulting value for the onClick
. Since calling it sets the state, that causes re-rendering, which does it again endlessly.
Your other version creates a function when the JSX is evaluated without calling it, which is why it works.
推荐阅读
- python - python搜索json以获取嵌套键值并获取路径
- flutter - 如何在按下按钮时下载 Flutter Web 应用程序?
- visual-studio-code - VSCode 在启动时打开一个非默认终端
- json - 是否可以将 json 文件上传到谷歌驱动器并通过共享链接将其提取到 Flutter 中?
- python - 如何创建一个以数组为成员的数组对象?
- less - 带有 LESS 配置问题的 stylelint
- sharepoint - 使用 Azure 数据工厂更改 SharePoint 中的文件目录
- python - 我的 Google 帐户中 Google Colab 中的 Python 语法有什么问题?
- django - category_id 需要一个数字,但得到了
看起来错误是因为
obj.category_id
在序列化程序中与多对多关系有关。错误:
类型错误:字段 'category_id' 需要一个数字,但在 0x0000025
- python - 对象从左向右移动但不从右向左移动