React-Native: FlatList每次都重新渲染每个项目

3

我有一个FlatList,它接收一个项目数组。当我滚动到底部时,我会将更多的项目添加到该数组的末尾并显示给用户。

问题是每个项目在我们添加到项目数组时都会被渲染,有时甚至会被渲染两次。

这里简化了代码。/r/reactnative无法回答这个问题。

constructor(props) {
super(props);
this.state = {itemsTest: ['A', 'A', 'A', 'A']}
}

render() {


// Key is fine, since none of my items are changing indexes. I am just adding new items.
return (

<FlatList

keyExtractor={(item,index) => index}

scroll

data={this.state.itemsTest}

renderItem={({item, index}) => <View style={{width: windowWidth}}><Text>{item}</Text></View>

onEndReached={() => this.nextItemsTest()}

onEndReachedThreshold={0.2}

</FlatList>
)
}







nextItemsTest() {

// From suggestions below, just add an element to this array.

console.log('nextItemsTest');

const x = ['A'];

// Have worked with many variations of setting state here. I don't think this is the issue.
this.setState((prevState) => ({itemsTest: [...prevState.itemsTest, ...x],}));}

这是输出结果。每当我的状态被设置时,每个单独的项目都会重新渲染(甚至两次)。

我只想重新渲染没有改变的项目。谢谢。

enter image description here

1个回答

5

不要直接在你的 flatlist 渲染中使用 View,你可以创建另一个纯组件来代替。这样当数据发生变化时,它将只重新渲染一次。例如,在你的情况下,每个项目只会重新渲染一次。

以下是解决方案:

首先,创建一个像这样的纯组件:

class SmartView extends PureComponent {
  render() {
    const {item, index} = this.props;
    return (
      <View style={{height: 300}}>
        {console.log('rendering', index)}
        <Text>{item}</Text>
      </View>
    );
  }
}

然后在您的flatlist中将 View 替换为 SmartView ,如下所示:

 <FlatList
        keyExtractor={(item, index) => index.toString()}
        data={this.state.itemsTest}
        renderItem={({item, index}) => <SmartView item=                                
                                        {item} index={index} />}
        onEndReached={() => this.nextItemsTest()}
        onEndReachedThreshold={0.2}
      />


如何从SmartView类调用另一个类的函数?例如,您希望能够点击在flatlist中渲染的其中一项,并且函数在另一个类中被调用(而不是在SmartView类中)。 - showtime

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接