首頁 > web前端 > js教程 > 在 React 的 Render 方法中綁定或內聯箭頭函數時如何避免效能問題?

在 React 的 Render 方法中綁定或內聯箭頭函數時如何避免效能問題?

Linda Hamilton
發布: 2024-11-15 10:35:02
原創
622 人瀏覽過

How to Avoid Performance Issues When Binding or Inlining Arrow Functions in React's Render Method?

How to Avoid Bind or Inline Arrow Functions Inside the Render Method

In React components, it's crucial to avoid binding or inlining arrow functions inside the render method to optimize performance. During re-rendering, new methods are created instead of reusing the old ones, resulting in performance issues.

Consider the following example:

<input onChange={this._handleChange.bind(this)} />
登入後複製

To address this, we can bind the _handleChange method in the constructor:

constructor(props) {
  super(props);
  this._handleChange = this._handleChange.bind(this);
}
登入後複製

Or, alternatively, we can use the property initializer syntax:

_handleChange = () => {};
登入後複製

However, challenges arise when we need to pass additional parameters to the onClick handler. For instance, in a todo app, we might need to delete an item from an array based on its index or name.

todos.map(el => <div key={el} onClick={this._deleteTodo.bind(this, el)}>{el}</div>)
登入後複製

This approach creates a new callback with each component render, as mentioned in the documentation.

Alternatives to Binding Inside the Render Method

1. Create a Child Component:

Move the content inside the map function to a separate child component and pass the values as props. This way, the function can be called from the child component and pass the value to the function passed down as props.

Parent:

deleteTodo = (val) => {
  console.log(val);
};

todos.map((el) => <MyComponent val={el} onClick={this.deleteTodo} />);
登入後複製

Child Component (MyComponent):

class MyComponent extends React.Component {
  deleteTodo = () => {
    this.props.onClick(this.props.val);
  };

  render() {
    return <div onClick={this.deleteTodo}>{this.props.val}</div>;
  }
}
登入後複製

Sample Snippet:

class Parent extends React.Component {
  _deleteTodo = (val) => {
    console.log(val);
  };

  render() {
    var todos = ['a', 'b', 'c'];
    return (
      <div>
        {todos.map((el) => (
          <MyComponent key={el} val={el} onClick={this._deleteTodo} />
        ))}
      </div>
    );
  }
}

class MyComponent extends React.Component {
  _deleteTodo = () => {
    console.log('here');
    this.props.onClick(this.props.val);
  };

  render() {
    return <div onClick={this._deleteTodo}>{this.props.val}</div>;
  }
}

ReactDOM.render(<Parent />, document.getElementById('app'));
登入後複製

By implementing these alternatives, we can avoid binding or inlining arrow functions inside the render method, ensuring the proper performance and reusability of the component.

以上是在 React 的 Render 方法中綁定或內聯箭頭函數時如何避免效能問題?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板