0

如何創建僅顯示具有一種「狀態」類型的數據的多個平面列表?如何使用React Native中的過濾數據生成多個平面列表

例如:

  • 一個Flatlist用於狀態=== 'INPROGRESS'
  • 一個Flatlist用於狀態=== '完成'
  • 一個Flatlist用於狀態=== 「無法'

所有數據都在數組'goallist'中,該數組來自Firebase數據庫。

我真的很感謝你對此的幫助。

import React, { Component } from 'react'; 
 
import { Text, FlatList, View, Image, TouchableOpacity, Alert } from 'react-native'; 
 
import firebase from 'firebase'; 
 
import { Button, Card, CardSection } from '../common'; 
 
import styles from '../Styles'; 
 

 
class List extends Component { 
 

 
    static navigationOptions = { 
 
     title: 'List', 
 
    } 
 

 
    constructor(props) { 
 
     super(props); 
 

 
     this.state = { 
 
      goallist: '', 
 
      loading: false, 
 
    }; 
 
    } 
 

 
componentDidMount() { 
 
    this.setState({ loading: true }); 
 
    const { currentUser } = firebase.auth(); 
 
    const keyParent = firebase.database().ref(`/users/${currentUser.uid}/goalProfile`); 
 
    keyParent.on(('child_added'), snapshot => { 
 
     const newChild = { 
 
      key: snapshot.key, 
 
      goal: snapshot.val().goal, 
 
      status: snapshot.val().status 
 
     }; 
 
     this.setState((prevState) => ({ goallist: [...prevState.goallist, newChild] })); 
 
     console.log(this.state.goallist); 
 
     }); 
 

 
this.setState({ loading: false }); 
 
} 
 

 
onRenderItem = ({ item }) => (
 
    <TouchableOpacity onPress={this.showAlert}> 
 
     <Text style={styles.listStyle}> 
 
      { item.goal } { item.key } 
 
     </Text> 
 
    </TouchableOpacity> 
 
); 
 

 
showAlert =() => { 
 
    Alert.alert(
 
     'Did you succeed or fail?', 
 
     'Update your status', 
 
    [ 
 
     { text: 'Completed?', 
 
       onPress:() => console.log('Completed Pressed'),    }, 
 
     { text: 'Failed?', 
 
       onPress:() => console.log('Failed Pressed'), 
 
     }, 
 
     { text: 'Cancel', 
 
       onPress:() => console.log('Cancel Pressed'), 
 
       style: 'cancel' }, 
 
    ], 
 
     { cancelable: false } 
 
    ); 
 
} 
 

 
keyExtractor = (item) => item.key; 
 

 
render() { 
 
    return (
 
    <Card> 
 

 
     <View style={{ flex: 1 }}> 
 
     <FlatList 
 
      data={this.state.goallist} 
 
      keyExtractor={this.keyExtractor} 
 
      extraData={this.state} 
 
      renderItem={this.onRenderItem} 
 
     /> 
 
     </View> 
 

 
    </Card> 
 
    ); 
 
    } 
 
} 
 

 
export { List };

回答

0

你只需要修改onRenderItem功能如下使一些特定的對象(這Flatlist只顯示INPROGRESS對象):

onRenderItem = ({ item }) => { 
    if (item.type === 'inProgress') { 
    return (
     <TouchableOpacity onPress={this.showAlert}> 
     <Text style={styles.listStyle}> 
      { item.goal } { item.key } 
     </Text> 
     </TouchableOpacity> 
    ) 
    } else { return null; } 
}; 
+0

謝謝。你的解決方案回答了我的問題並且工作。沒有代碼的「else return null」部分,我能夠做到這一點。 – courti