react-native | 重新渲染平面列表

IT技术 reactjs react-native react-native-flatlist
2021-05-19 04:35:39

我有一个列表:数据。然后当我更新列表时,它会再次呈现所有元素。例如,假设有 10 个项目。其中之一发生了变化。10 个项目再次渲染。但由于其中 9 个是相同的,因此不应再次渲染它们。我能怎么做?

const Item =({item}) => (
   <Text>{item.name}</Text>
)

const List = () => {
  const [data, setData] = useState([..]);

  return (
     <FlatList
        data={data}
        renderItem = {Item}
     >
)}
export default List;
1个回答

你必须使用extraDatapropsFlatlist

根据文档:

By passing extraData={this.state} to FlatList we make sure FlatList will re-render itself when the state.selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.

或者你可以在你的renderitem组件中实现 shouldComponentUpdate并在你想要渲染你的组件时进行检查。