【发布时间】:2017-04-24 09:03:09
【问题描述】:
我已经阅读了很多关于() => {} 语法的使用、构造函数中的绑定、道具中的绑定等的文章。但据我了解,绑定this 在性能方面的成本很高,而且做与箭头函数的自动绑定代价高昂,因为它每次都会创建一个新的匿名函数。
那么处理这个问题的最高效的“反应方式”是什么?
构造函数中的绑定似乎对于不需要传递参数的函数效果很好,如下所示:
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
但是我们如何处理传递参数的绑定函数,而不将其绑定在 prop 中,如下所示:
<li onClick={this.handleClick.bind(this, item.id)} />{item.name}</li>
在构造函数中绑定this,然后在prop 中绑定null 或undefined 是否会导致绑定函数只绑定一次?
如有任何误解,请随时纠正我。似乎这个问题的解决方案应该更广为人知和普遍......那就是如果我不只是生活在岩石下!
编辑:
即使有抽象,点击处理程序不是与每个单独的项目渲染绑定吗?
在here 文章中,他们给出了这个例子来避免绑定点击处理程序,但是因为 React.createClass 会自动绑定方法,我看不出这实际上是如何绑定的每个项目都渲染?
var List = React.createClass({
render() {
let { handleClick } = this.props;
// handleClick still expects an id, but we don't need to worry
// about that here. Just pass the function itself and ListItem
// will call it with the id.
return (
<ul>
{this.props.items.map(item =>
<ListItem key={item.id} item={item} onItemClick={handleClick} />
)}
</ul>
);
}
});
var ListItem = React.createClass({
render() {
// Don't need a bind here, since it's just calling
// our own click handler
return (
<li onClick={this.handleClick}>
{this.props.item.name}
</li>
);
},
handleClick() {
// Our click handler knows the item's id, so it
// can just pass it along.
this.props.onItemClick(this.props.item.id);
}
});
有人能解释一下吗? 这看起来不只是避免绑定每个 ListItem 渲染,但由于 React.createClass 中的自动绑定,它仍然可以吗?
我用class List extends Component 语法而不是createClass 尝试了这个示例,并且this.handleClick 未定义,因为handleClick 方法未绑定到类。
归根结底,这似乎只是消除了冗长,并没有通过减少方法绑定来真正提高性能...
【问题讨论】:
-
性能在这里绝对不是问题。在看到任何性能问题之前,您必须以 60fps 的速度更新数千个元素,而 React 本身将成为您的瓶颈,而不是垃圾收集,所以没关系。
-
我没有意识到这一点。感谢您的评论!
标签: javascript reactjs ecmascript-6