How to avoid bind or inline arrow functions inside render method

前端 未结 4 1461
暖寄归人
暖寄归人 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:48

    How to avoid this way of binding inside render method or what are the alternatives of this?

    If you care about re-rendering then shouldComponentUpdate and PureComponent are your friends and they will help you optimize rendering.

    You have to extract "Child" component from the "Parent" and pass always the same props and implement shouldComponentUpdate or use PureComponent. What we want is a case when we remove a child, other children shouldn't be re-rendered.

    Example

    import React, { Component, PureComponent } from 'react';
    import { render } from 'react-dom';
    
    class Product extends PureComponent {
      render() {
        const { id, name, onDelete } = this.props;
    
        console.log(` render()`);
        return (
          
  • {id} - {name}
  • ); } } class App extends Component { constructor(props) { super(props); this.state = { products: [ { id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }, ], }; this.handleDelete = this.handleDelete.bind(this); } handleDelete(productId) { this.setState(prevState => ({ products: prevState.products.filter(product => product.id !== productId), })); } render() { console.log(` render()`); return (

    Products

      { this.state.products.map(product => ( )) }
    ); } } render(, document.getElementById('root'));

    Demo: https://codesandbox.io/s/99nZGlyZ

    Expected behaviour

    • render()

    When we remove only is re-rendered.

    • render()

    To see those messages in demo, open the dev tools console.

    The same technique is used and described in article: React is Slow, React is Fast: Optimizing React Apps in Practice by François Zaninotto.

提交回复
热议问题