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

时间:2020-08-26 13:22:55

标签: javascript reactjs react-native

因此,我有一个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 个答案:

答案 0 :(得分:2)

您可以创建另一个纯粹的组件,而不是直接在平面列表渲染中使用“视图”。因此它只会在数据更改时重新渲染。例如,对于您的情况,它只会重新渲染每个项目一次。

这是解决方法

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

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