How to avoid bind or inline arrow functions inside render method

前端 未结 4 1399
暖寄归人
暖寄归人 2020-11-22 06:10

We should avoid method binding inside render because during re-rendering it will create the new methods instead of using the old one, that will affect the performance.

4条回答
  •  情话喂你
    2020-11-22 06:56

    This answer https://stackoverflow.com/a/45053753/2808062 is definitely exhaustive, but I'd say fighting excessive re-renders instead of just re-creating the tiny callback would bring you more performance improvements. That's normally achieved by implementing a proper shouldComponentUpdate in the child component.

    Even if the props are exactly the same, the following code will still re-render children unless they prevent it in their own shouldComponentUpdate (they might inherit it from PureComponent):

    handleChildClick = itemId => {}
    
    render() {
        return this.props.array.map(itemData => 

    Proof: https://jsfiddle.net/69z2wepo/92281/.

    So, in order to avoid re-renders, the child component has to implement shouldComponentUpdate anyway. Now, the only reasonable implementation is completely ignoring onClick regardless of whether it has changed:

    shouldComponentUpdate(nextProps) {
        return this.props.array !== nextProps.array;
    }
    

提交回复
热议问题