假设我有一个名为
generateList()
的函数,它会更新状态并将其映射为<li>
元素的onClick
事件。<li className="some-classname"}
onClick={this.generateList('product')}> Product </li>
有时候我会遇到这样的错误:
警告:setState(...):无法在现有状态转换期间更新(例如在render中)。渲染方法应该是props的纯函数...
我在互联网上搜索解答,找到了像这个答案:
<li className="some-classname"}
onClick={this.generateList.bind(this, 'product')}> Product </li>
但我也看到了一个答案(在Github上,但似乎找不到它):
<li className="some-classname"}
onClick={() => this.generateList('product')}> Product </li>
主要区别是什么?哪个更适合和高效?当将函数映射到onClick
或作为React组件的属性时(我大多数情况下使用它),我们为什么要使用.bind
和() =>
这样的东西呢?