[英]How to update rendered flat/section list items immediately React Native
我正在创建一个ContactListScreen
。 ContactListScreen
的直接子元素是ContactItems
, ContactItems
是一个 sectionList ,它呈现每个ContactItem
。 但问题出现了,因为我的ContactItems
应该是多选的。
我将selectedContacts
数组从我的状态传递给每个ContactItem
。 我这里使用的逻辑是ContactItem
检查selectedContacts
的长度是否为 0。 如果长度为零,它不应该呈现任何selectItemView
,如果我选择一个项目,它应该使用回调将自己推送到selectedContacts
。 但问题是子组件( ContactItem
)在我选择取消选择项目两次或三次之前不会更新。 我怎样才能让它工作?
ContactList.tsx 的一部分
class ContactList extends Component {
this.state = {
loading: false,
error: null,
data: [],
selectedItems: []
};
handleSelectionPress = (item) => {
this.setState(prevState => {
const { selectedItems } = prevState;
const isSelected = selectedItems.includes(item);
return {
selectedItems: isSelected
? selectedItems.filter(title => title !== item)
: [item, ...selectedItems],
};
});
};
renderItem(item: any) {
return <ContactItem item={item.item}
isSelected={this.state.selectedItems.includes(item.item)}
onPress={this.handleSelectionPress}
selectedItems={this.state.selectedItems}
/>;
}
render() {
return (
<View style={styles.container}>
<SectionList
sections={this.state.data}
keyExtractor={(item, index) => item.id}
renderItem={this.renderItem.bind(this)}
renderSectionHeader={({section}) => (
section.data.length > 0 ?
<Text>
{section.title}
</Text> : (null)
)}
/>
</View>
);
}
}
ContactItem.tsx 的一部分
class ContactItem extend Component {
render() {
const checkBox = <TouchableOpacity onPress={() => {
this.props.onPress(this.props.item)
}
} style={this.props.selectedItems.length > 0 && {display: 'none'}}>
{!this.props.isSelected ?
<View style={{borderRadius: 10, height: 20, width: 20, borderColor: "#f0f", borderWidth: 1}}>
</View> : <View style={{
borderRadius: 10,
height: 20,
width: 20,
borderColor: "#f0f",
borderWidth: 1,
backgroundColor: "#f0f"
}}>
</View>}
</TouchableOpacity>
return (
<View style={this.styles.contactsContainer}>
<TouchableOpacity
onLongPress={() => this.props.onPress(this.props.item)}>
<View style={this.styles.contactInfo}>
{checkBox}
</View>
</TouchableOpacity>
</View>
);
}
注意:我工作的地方不使用功能组件。
我不是 100% 确定这一点,但我有一种感觉,问题是SectionList
组件没有触发它的更新,因为提供的sections={this.state.data}
属性永远不会改变。
处理此问题的最简单方法是将selectedItems
作为extraData属性添加到部分列表:
<SectionList
sections={this.state.data}
extraData={this.state.selectedItems}
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.