状态改变时 ListHeaderComponent 不重新渲染
ListHeaderComponent Does Not Re-render When State Changes
我正在使用带有 ListHeaderComponent 的 FlatList。
<FlatList
data={this.state[this.feeds].edges}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
onEndReached={this.onFetchFeeds}
onRefresh={this.onRefresh}
refreshing={this.state.isRefreshing}
ListHeaderComponent={this.renderBody}
/>
我做了一个渲染 ListHeaderComponent。
renderBody = () => {
if (this.props.body)
return this.props.body;
并且this.props.body
由父组件交付。
<Feeds
body={<View>
{ this.state.suggestions.slice(0, 3).map((channel, index) =>
<ChannelSlot key={index} {...channel}/>)}
{ this.state.suggestions.length > 3 && !this.state.seeMore ?
<TouchableOpacity onPress={() => this.setState({seeMore: true})}>
<Text style={styles.moreButton}>See More</Text>
</TouchableOpacity> : null}
{ this.state.seeMore && this.state.suggestions.slice(3, 15).map((channel, index) => <ChannelSlot key={index} {...channel}/>)}
</View>}
/>
问题是即使 this.state.seeMore
发生变化,传递给正文的组件也不会重新呈现。它仅在 FlatList 上完成 'pull-to-refresh' 时才重新呈现。然后它会更新。我的代码有什么问题?
由于您正在为 ListHeaderComponent
使用一个函数,即使该函数的 return 值可能不同,该道具的值也不会改变。所以 FlatList
不知道 re-render。调用渲染函数来生成渲染元素,因此 renderBody()
的 return 值的任何变化都会导致 FlatList
header.[= 的 re-render。 15=]
<FlatList
...
// note the function call here instead of passing the function itself
ListHeaderComponent={this.renderBody()}
/>
我正在使用带有 ListHeaderComponent 的 FlatList。
<FlatList
data={this.state[this.feeds].edges}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
onEndReached={this.onFetchFeeds}
onRefresh={this.onRefresh}
refreshing={this.state.isRefreshing}
ListHeaderComponent={this.renderBody}
/>
我做了一个渲染 ListHeaderComponent。
renderBody = () => {
if (this.props.body)
return this.props.body;
并且this.props.body
由父组件交付。
<Feeds
body={<View>
{ this.state.suggestions.slice(0, 3).map((channel, index) =>
<ChannelSlot key={index} {...channel}/>)}
{ this.state.suggestions.length > 3 && !this.state.seeMore ?
<TouchableOpacity onPress={() => this.setState({seeMore: true})}>
<Text style={styles.moreButton}>See More</Text>
</TouchableOpacity> : null}
{ this.state.seeMore && this.state.suggestions.slice(3, 15).map((channel, index) => <ChannelSlot key={index} {...channel}/>)}
</View>}
/>
问题是即使 this.state.seeMore
发生变化,传递给正文的组件也不会重新呈现。它仅在 FlatList 上完成 'pull-to-refresh' 时才重新呈现。然后它会更新。我的代码有什么问题?
由于您正在为 ListHeaderComponent
使用一个函数,即使该函数的 return 值可能不同,该道具的值也不会改变。所以 FlatList
不知道 re-render。调用渲染函数来生成渲染元素,因此 renderBody()
的 return 值的任何变化都会导致 FlatList
header.[= 的 re-render。 15=]
<FlatList
...
// note the function call here instead of passing the function itself
ListHeaderComponent={this.renderBody()}
/>