And*_*ung 3 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],}));}
Run Code Online (Sandbox Code Playgroud)
这是输出。每次设置状态时,每个项目都会重新渲染(甚至两次)。
我只想重新渲染未更改的项目。谢谢。
您可以创建另一个纯组件组件,而不是直接在平面列表渲染中使用视图。所以它只会在数据发生变化时重新渲染。例如,对于您的情况,它仅重新渲染每个项目一次。
这是解决方案
1首先创建一个像这样的纯组件
class SmartView extends PureComponent {
render() {
const {item, index} = this.props;
return (
<View style={{height: 300}}>
{console.log('rendering', index)}
<Text>{item}</Text>
</View>
);
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样在平面列表中将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}
/>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4582 次 |
最近记录: |