简体   繁体   English

在平面列表中加载初始数据

[英]Loading initial data in a flatlist

I am using React-native to create an app for a school district.我正在使用 React-native 为学区创建应用程序。 On one screen I want to be able to search through the staff directory to find a staff member.在一个屏幕上,我希望能够搜索员工目录以查找员工。 I am using a Flatlist to display each staff member and a TextInput to search through the list.我正在使用 Flatlist 来显示每个员工,并使用 TextInput 来搜索列表。 The issue I am having with my current code is that upon the initial screen load my Flatlist does not render any components.我当前代码遇到的问题是,在初始屏幕加载时,我的 Flatlist 不会呈现任何组件。 When I enter text into my TextInput then the flatlist renders.当我在 TextInput 中输入文本时,会呈现平面列表。 How can I fix this so that my data is displayed in the flatlist when initially loading.我该如何解决这个问题,以便我的数据在最初加载时显示在平面列表中。

const StaffScreen = props => {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState();
    const [searchTerm, setSearchTerm] = useState('');
    const [data, setData] = useState(staff);
    const staff = useSelector(state => state.staff.staffMembers);
    const dispatch = useDispatch();

    const loadStaff = useCallback(async () => {
        setError(null);
        setIsLoading(true);
        try {
            await dispatch(staffActions.loadStaff());

        } catch (err) {
            setError(err.message)
        }
        setIsLoading(false);
    }, [dispatch, setIsLoading, setError]);

    useEffect(() => {
        const willFocusSub = props.navigation.addListener('willFocus', loadStaff);
        return () => {
            willFocusSub.remove();
        };
    }, [loadStaff]);

    useEffect(() => {
        loadStaff();
    }, [dispatch, loadStaff]);

    const textChangeHandler = event => {
        setSearchTerm(event);
    }

    useEffect(()=> {
        const searchItem = searchTerm;
        const results = staff.filter(staffMember => staffMember.firstName.includes(searchItem) 
        || staffMember.lastName.includes(searchItem) 
        || staffMember.jobTitle.includes(searchItem) );
        setData(results)
    }, [searchTerm]);


    if (error) {
        return <View style={styles.container}>
            <View style={{ alignSelf: 'flex-start' }}><RichHeader title='Staff Directory' /></View>
            <View style={styles.centered}>
                <Text style={styles.errorText}>{error.toString()} </Text>
                <Button title='Try Again' color={Colors.accent} onPress={loadStaff} />
            </View>
        </View>
    }

    if (isLoading) {
        return <View style={styles.container}>
            <View style={{ alignSelf: 'flex-start' }}><RichHeader title='Staff Directory' /></View>
            <View style={styles.search}>
                <TextInput style={styles.textInput} />
                <Ionicons name={Platform.OS === 'android' ? 'md-search' : 'ios-search'} size={35} color={Colors.darkerAccent} />
            </View>
            <View style={styles.centered}>
                <ActivityIndicator size='large' color={Colors.accent} />
            </View>
        </View>
    }

    return (
        <View style={styles.container}>
            <View style={{ alignSelf: 'flex-start' }}><RichHeader title='Staff Directory' /></View>
            <View style={styles.search}>
                <TextInput 
                    style={styles.textInput} 
                    onChangeText={textChangeHandler}
                    value={searchTerm}
                    />
                <Ionicons name={Platform.OS === 'android' ? 'md-search' : 'ios-search'} size={35} color={Colors.darkerAccent} />
            </View>
            <FlatList
                data={data}
                keyExtractor={item => item.emailAddress}
                renderItem={
                    itemData => (
                        <StaffItem
                            first={itemData.item.firstName}
                            last={itemData.item.lastName}
                            title={itemData.item.jobTitle}
                            ext={itemData.item.extension}
                            email={itemData.item.emailAddress}
                        />
                    )
                } />
        </View>
    )
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    textInput: {
        height: 30,
        width: '90%',
        fontSize: 24,
        paddingLeft: 20,
        color: Colors.darkerAccent
    },
    search: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingTop: 10,
        backgroundColor: 'white',
        paddingRight: 10,
        borderBottomColor: Colors.accent,
        borderBottomWidth: 1,
        borderTopColor: Colors.accent,
        borderTopWidth: 1,
        marginVertical: 10
    },
    centered: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    errorText: {
        fontFamily: 'open-sans-bold',
        fontSize: 20,
        textAlign: 'center',
        color: Colors.accent,
        textDecorationColor: Colors.darkerAccent
    }
});

export default StaffScreen;

Any help would be appreciated.任何帮助,将不胜感激。

To show your data when your component loads, you should use useEffect with an empty array as second argument要在组件加载时显示数据,您应该使用带有空数组的 useEffect 作为第二个参数

useEffect(() => {
    loadStaff();
}, []);

I don't sure it is that but我不确定是不是这样,但是


  const [data, setData] = useState(staff);
  const staff = useSelector(state => state.staff.staffMembers);

you are using staff before declaring it as first values for data , what's later comes as FlatList data at initial render您在将其声明为data的第一个值之前使用staff ,后来在初始渲染时作为FlatList数据出现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM