Câu hỏi phỏng vấn Reactjs
Câu hỏi

What would be the common mistake of function being called every time the component renders?

Câu trả lời

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:

  1. Binding the function in the constructor and then passing the bound function:
constructor(props) {
  super(props);
  this.activatePlaylist = this.activatePlaylist.bind(this);
}

// ...

<button onClick={() => this.activatePlaylist(playlist.playlist_id)}>Play</button>
  1. Using an arrow function in the render method to wrap the function call:
<button onClick={() => this.activatePlaylist(playlist.playlist_id)}>Play</button>
  1. Binding the function directly in the JSX (not recommended due to potential performance issues):
<button onClick={this.activatePlaylist.bind(this, playlist.playlist_id)}>Pla...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What happens when you call setState ?

expert

What is a Pure Function?

entry

What are the major features of ReactJS?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào