reactjs - Why are Arrow Functions in ReactJS considered as property?
问题描述
So, I've tried two different approaches as per need, i.e with Arrow Functions and Non-Arrow Functions, and while writing the code I noticed something odd about both of these, the non-arrow function i.e.
close() {
this.setState({
show: false
});
}
are considered as method(s) which is true as they are functions,
But when I write an Arrow function such as:
goToNextPage = () => {
this.setState(({ page }) => ({ page: page + 1 }));
};
It is considered a property, I quite do not understand this behavior. Is this something wrong with VSCode or it is an entirely different thing?
解决方案
class MyClass { aClassProperty = <whatever_value>; }
意味着您正在为类的每个新实例创建一个新的类属性。该属性可以是您喜欢的任何值,但在这种情况下,该属性是一个箭头函数,所以它是正确的。
aMethod()
在类的每个实例之间共享,但是在 React 中,您通常通过将其绑定到构造函数来创建一个新函数this
,因此最终结果是相同的。
推荐阅读
- c# - 如何对列表进行排序
通过对象中的属性,根据属性的逗号分隔字符串 - powershell - 外壳 | 有没有办法过滤掉数组中小于 6 个月大的项目?
- angular - 如何将开源 Angular 组件的本地克隆版本包含到 Angular 项目中?
- html - HTML 和 CSS 表格/网格设计
- html - 如何在 CSS 蒙版内有阴影?
- javascript - 将 TensorFlowJS MobileNet + KNN 保存到 TFLite
- flutter - Flutter:如何为两个小部件设置一个水龙头处理程序?
- xml - 如何使用 XMLStarlet / Xpath 选择里面的文本但排除一些内在
- java - 字符串开头的Java不可见空格
- ruby-on-rails - 如何在Ruby中迭代没有已知深度的深层嵌套哈希