React Native中使用FlatList仅展示指定ID数据的问题求助
解决React Native FlatList展示特定ID数据而非全部的问题
嘿,我看了你的问题和代码,核心问题很明确:你没有对staffLeave数组做筛选,直接把整个数组传给了FlatList的data属性,所以才会显示所有ID的数据。下面给你一步步解决:
步骤1:添加特定ID的筛选逻辑
你需要先用Array.filter()方法过滤数组,只保留和目标ID匹配的项。从你的代码里看到有this.state.staff_id,假设这就是你要展示的特定ID,那可以在渲染FlatList前先处理数据:
// 筛选出匹配目标ID的数据 const filteredLeaveData = this.state.staffLeave.filter(item => { // 这里替换成你实际的ID匹配逻辑,比如item.id === 目标ID return item.staff_id === this.state.staff_id; });
步骤2:将筛选后的数据传给FlatList
把FlatList的data属性从this.state.staffLeave替换成上面的filteredLeaveData,这样就只会渲染符合条件的项了。
额外修复:语法错误
另外注意你原代码里有个小bug:item.staff_name.toUpperCase()()多了一对括号,会导致运行报错,应该改成item.staff_name?.toUpperCase()(加?.可选链是为了避免staff_name为null/undefined时报错),同时includes(this.state.text.toUpperCase())也不需要额外括号。
整合后的完整代码片段
把这些修改整合到你的代码里,大概是这样:
{this.state.view_access == false ? ( <NoAccessScreen></NoAccessScreen> ) : this.state.isLoading ? ( <View style={[components.alignCenter, components.justifyCenter, components.pad_10]} > <ActivityIndicator /> </View> ) : ( <> {/* 先筛选目标ID的数据 */} {(() => { const filteredLeaveData = this.state.staffLeave.filter(item => item.staff_id === this.state.staff_id); return ( <FlatList data={filteredLeaveData} renderItem={({ item }) => ( this.state.text == null || item.staff_name?.toUpperCase().includes(this.state.text.toUpperCase()) ? ( <TouchableOpacity> <View style={[components.listContainer]} > <View style={components.cardContainer}> <View style={[components.dotContainer]} > <View style={[components.flex_row, components.justifyAlignStart, { padding: 5 }]}> <View style={{ width: '75%' }}> { item.staff_name != null ? <View style={{ width: '100%' }}> <Text style={[components.titleTextStyle]}>{item.name}</Text> </View> : null } { item.centre_name != null ? <View style={{ width: '100%' }}> <Text style={[components.titleTextStyle]}>{item.centre_name}</Text> </View> : null } { item.leave_days != null ? <View style={{ width: '100%' }}> <Text style={[components.titleTextStyle]}>{item.leave_days}</Text> </View> : null } { item.date_range != null ? <View style={{ width: '100%' }}> <Text style={[components.titleTextStyle]}>{item.date_range}</Text> </View> : null } { item.approved_by != null ? <View style={{ width: '100%' }}> <Text style={[components.titleTextStyle]}>{item.approved_by}</Text> </View> : null } { item.approved_date != null ? <View style={{ width: '100%' }}> <Text style={[components.titleTextStyle]}>{item.approved_date}</Text> </View> : null } { item.status != null ? <View style={{ width: '100%' }}> <Text style={[components.titleTextStyle]}>{item.status}</Text> </View> : null } </View> </View> </View> </View> </View> </TouchableOpacity> ) : null )} keyExtractor={(item, index) => index.toString()} extraData={this.state} nestedScrollEnabled={true} /> ) })()} </> )}
补充说明
- 如果你的目标ID是从路由参数里获取的(比如从其他页面跳转传过来的),可以在
componentDidMount生命周期里先把这个ID存到this.state里,再用它来筛选数据。 Array.filter()会返回一个新数组,不会修改原数组,符合React的状态更新原则。
内容的提问来源于stack exchange,提问作者Intern 2
相关产品推荐
相关产品推荐

