Câu hỏi phỏng vấn React Native
Câu hỏi

How do you re-render a FlatList?

Câu trả lời

To re-render a FlatList in React Native, you can use several techniques depending on the specific requirements and the nature of the changes in your data. Here are some common methods:

1. Using extraData Prop

The extraData prop is used to tell the FlatList to re-render when the state or props it depends on change. This is particularly useful when the data array itself does not change, but some other state that affects the rendering does.

<FlatList
  data={this.state.data}
  renderItem={this.renderItem}
  keyExtractor={(item) => item.id}
  extraData={this.state}
/>

In this example, extraData={this.state} ensures that the FlatList re-renders whenever any part of the component's state changes[1][13][14].

2. Updating the Data Array

If the data array itself changes, you can simply update the state that holds the data. React will automatically re-render the FlatList when the state changes.

this.setState({ data: newData });

Ensure that you create a new array rather than mutating the existing one to trigger a re-render[1][10].

3. Using RefreshControl for Pull-to-Refresh

To implement pull-to-refresh functionality, you can use the RefreshControl component. This component is used inside a FlatList to handle the pull-to-refresh gesture.

<FlatList
  data={this.state.data}
  renderItem={this.renderItem}
  keyExtractor={(item) => item.id}
  refreshControl={
    <RefreshControl
      refreshing={this.state.refreshing}
      onRefresh={this.handleRefresh}
    />
  }
/>

In this example, refreshing is a boolean state that indicates whether the list is currently refreshing, and handleRefresh is a function that fetches new data and updates the state[3][4][15].

4. Memoizing renderItem

To optimize performance and avoid unnecessary re-renders, you can memoize the renderItem function using React.memo or useCallback.

const renderItem = useCallback(({ item }) => {
  return <ItemComponent item={item} />;
}, []);

This ensures that renderItem is not recreated on every render, which can help with performance[9][10].

5. Using PureComponent or React.memo

If you are using class components, you can extend PureComponent to prevent unnecessary re-renders. For functional components, you can use React.memo.

const MyListItem = React.memo(({ item }) => {
  return <Text>{item.title}</Text>;
});

This ensures that the component only re-renders when its props change[9][10].

Example Code

Here is a complete example that combines some of these techniques:

`...

middle

middle

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

middle

What happens if you edit modules with exports that aren't React components in Fast Refresh?

middle

What are some best practices to consider for an action?

senior

How would you implement animations on events?

Bình luận

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

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