阅读When to Use Component or PureComponent中不要绑定渲染部分中的函数中的值,它提到不应该执行<CommentItem likeComment={() => this.likeComment(user.id)} />
而应该执行<CommentItem likeComment={this.likeComment} userID={user.id} />
,然后执行:
class CommentItem extends PureComponent {
...
handleLike() {
this.props.likeComment(this.props.userID)
}
...
}
因为当调用父的render方法时,会创建一个新函数(带有一个新引用)以传递给likeComment
,这将导致所有子节点重新呈现,即使数据本身都是相同的。
我对箭头函数如何绑定有点困惑,我想知道以下示例是否也会导致不良行为
_keyExtractor = (item, index) => String(index);
render() {
return (
<FlatList
...
keyExtractor={this._keyExtractor}
...>
</FlatList>
);
}
由于FlatList
是一个PureComponent(我相信),如果_keyExtractor
是容器父项,那么FlatList
的定义是否会重新呈现?
他在这里提到的reference
是对象参考,你知道{} === {}
是false
在javaScript函数中是对象,因此每次调用render时,都必须重新渲染子项,因为你传递了一个新函数。
(x => x) === (x => x) // false.
您提供的最后一个示例很好,因为该函数将始终保持其引用。
希望这段代码可以帮助你:
export default class PureComponent extends Component {
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
}
你甚至可以回复这个:
return !isEqual(this.props, nextProps) || !isEqual(this.state, nextState);
注意:
import {isEqual} from 'lodash';
import shallowCompare from 'react-addons-shallow-compare';
别忘了这些进口商品。
该组件将作为完美的PureComponent。