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.
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中文網其他相關文章!