What would be the common mistake of function being called every time the component renders?
What would be the common mistake of function being called every time the component renders?
The common mistake that leads to a function being called every time a component renders in React is when the function is invoked directly within the JSX, rather than being passed as a reference to an event handler. This typically happens when a developer includes parentheses after the function name within the JSX, which causes the function to execute during the rendering process.
For example, consider the following incorrect usage:
<button onClick={this.activatePlaylist(playlist.playlist_id)}>Play</button>
In this case, activatePlaylist
is being called immediately as the button
element is rendered, rather than being called in response to the onClick
event.
The correct approach is to pass a reference to the function, which can be done in several ways:
constructor(props) {
super(props);
this.activatePlaylist = this.activatePlaylist.bind(this);
}
// ...
<button onClick={() => this.activatePlaylist(playlist.playlist_id)}>Play</button>
<button onClick={() => this.activatePlaylist(playlist.playlist_id)}>Play</button>
<button onClick={this.activatePlaylist.bind(this, playlist.playlist_id)}>Pla...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào