可触摸不透明度在平面列表中响应非常慢

时间:2021-07-04 08:30:17

标签: javascript react-native

我正在创建一个 Instagram 克隆来学习 React Native,我已经创建了 Feed 页面,一切正常,但是 Like 按钮响应非常慢。每当我点击喜欢按钮时,它要么在第一次点击时没有响应,要么在 5-6 秒内响应。

我注意到在没有任何 Flatlist 的屏幕中通常会做出响应。但是带有 Flatlist 的屏幕会使组件变慢。但是,我尝试了 5 个列表项、20 个列表项、25 个列表项和 50 个列表项,结果相同。

我的代码

import React, {useEffect, useState} from 'react';
import { Alert, ImageBackground, SafeAreaView, Text, View, Button, FlatList, ActivityIndicator } from 'react-native';
// import { FlatList } from 'react-native-gesture-handler';
import { Pranah } from '../pranah/cust.js'; 
import axios from 'axios';
import base64 from 'react-native-base64';
import { uni } from '../css/uni.js';
import { colors } from '../pranah/colors.js';
import { UserPostHeader } from '../pranah/new.js';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {MainPostCont} from '../pranah/post.js';
import {TextPostCont} from '../pranah/text.js';
import { PostCaption } from '../pranah/mediaCaption.js';
import {BottomPost} from '../pranah/bottomPost.js';
import { TouchableOpacity } from 'react-native-gesture-handler';


function Feed({navigation}){
    const [FeedPosts, setFeedPosts] = useState([]);
    const [StartNum, setStartNum] = useState(0);
    const [launchcount, setlaunchcount] = useState(0);
    const [showProg, setProg] = useState(true);
    //UI FUNCTIONS FOR PROFILE PAGE
    // Feed Page Structural Functions
    
    function showPost({item, index}){
        return(
            <View>
                <UserPostHeader dp={item.dp} name={item.name} username={item.username}/>
                {item.type === "text" ? <TextPostCont text={item.caption} /> : <MainPostCont path={item.url}/>}
                <BottomPost Post={item.id} nav={navigation} liked={item.liked} fav={item.fav} index={index}
                    update={{
                        like:()=>{
                            let provList = FeedPosts;
                            provList[index].liked = true;
                            setFeedPosts([...provList]);
                            // setlaunchcount(prevState=>prevState+1);
                            // console.warn(launchcount);
                        }
                    }}
                />
                {item.type === "text" ? <PostCaption.TextPostCaption/> : <PostCaption.MediaPostCaption caption={item.caption} />}
            </View>
        );
    }

    function fetchFeeds(){
        AsyncStorage.getItem("mail").then((v)=>{
            if (v == null){
                Alert.alert(uni.lang("चेतावनी", "Warning"), uni.lang("लॉगिन क्रेडेंशियल नहीं मिल रहा है।", "Can't find Login Credentials."));
                navigation.replace("Login");
            }else{
                //FETCH FEEDS!
                AsyncStorage.getItem("pass").then((p)=>{
                    if (p == null){
                        Alert.alert(uni.lang("चेतावनी", "Warning"), uni.lang("लॉगिन क्रेडेंशियल नहीं मिल रहा है।", "Can't find Login Credentials.")); 
                        navigation.replace("Login");
                    }else{
                axios({
                    method: 'post',
                    url: uni.bind('feed'),
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    data: uni.string({
                      mail: v,
                      pass: base64.encode(p),
                      start: StartNum
                    })
                  })
                  .then((response)=>{
                    let data = response.data;
                    if (uni.logic(data) === "error"){
                        uni.Error();
                    }else if (uni.logic(data) === "invalid"){
                        AsyncStorage.setItem("mail", "");
                        AsyncStorage.getItem("pass", "");
                        navigation.replace("Login");
                    }else if(uni.logic(data) === "nomore" || uni.logic(data) === "followernull"){
                        //SOME CODE TO RUN
                        setProg(false);
                    }else{
                        setFeedPosts(data);
                        setStartNum(StartNum + 20);
                    }
                  })
                  .catch((e)=>{
                      uni.Error();
                  });
                }                
                });
            }
            
        });
    }


    useEffect(()=>{
        if (launchcount == 0){
        fetchFeeds();
        setlaunchcount(1);
        }
    }, []);

    function callMorePosts(){
        AsyncStorage.getItem("mail").then((v)=>{
            if (v == null){
                Alert.alert(uni.lang("चेतावनी", "Warning"), uni.lang("लॉगिन क्रेडेंशियल नहीं मिल रहा है।", "Can't find Login Credentials."));
                navigation.replace("Login");
            }else{
                //FETCH FEEDS!
                AsyncStorage.getItem("pass").then((p)=>{
                    if (p == null){
                        Alert.alert(uni.lang("चेतावनी", "Warning"), uni.lang("लॉगिन क्रेडेंशियल नहीं मिल रहा है।", "Can't find Login Credentials.")); 
                        navigation.replace("Login");
                    }else{
                axios({
                    method: 'post',
                    url: uni.bind('feed'),
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    data: uni.string({
                      mail: v,
                      pass: base64.encode(p),
                      start: StartNum
                    })
                  })
                  .then((response)=>{
                    let data = response.data;
                    if (uni.logic(data) === "error"){
                        uni.Error();
                    }else if (uni.logic(data) === "invalid"){
                        AsyncStorage.setItem("mail", "");
                        AsyncStorage.getItem("pass", "");
                        navigation.replace("Login");
                    }else if(uni.logic(data) === "nomore" || uni.logic(data) === "followernull"){
                        //SOME CODE TO RUN
                        // alert('END');
                        setProg(false);
                    }else{
                        setFeedPosts(prevState=>[
                            ...prevState,
                            ...data
                        ]);
                        setStartNum(StartNum + 20);
                    }
                  })
                  .catch((e)=>{
                      uni.Error();
                    // alert(e);/
                  });
                }                
                });
            }
            
        });
    }

    // Header (Everything Label)
    function HeadForFeed(){
        return(
            <Text
                style={{
                    fontSize: 40,
                    fontWeight: "bold",
                    margin: 25
                }}
            >{uni.lang("सबकुछ ||", "Everything.")}
                {StartNum}
            </Text>
        );
    }

    // Footer (End of List)
    function FootForFeed(){
        return(
            <View style={{
                width: "100%",
                alignItems: "center",
                justifyContent: "center",
                alignContent: "center",
                fontSize: 20
            }}>
                {showProg == true ? <ActivityIndicator size="large" color={colors.primary}/> : <Text>{uni.lang("|| आप सूचि के अंत पे हैं || ", "You have reached the end.")}</Text> }
            </View>
        );
    }

    return(
        <SafeAreaView
            style={{
                width: "100%",
                height: "100%"
            }}
        >
            <Pranah.stb />
            <ImageBackground
                style={{
                    width: "100%",
                    height: "100%"
                }}
                source={require('../assets/background_mobile.png')}
            >
                <Pranah.pranahHead onPress={()=>{setStartNum(0);fetchFeeds()}} />

                <FlatList 
                    ListHeaderComponent={HeadForFeed}
                    data={FeedPosts}
                    renderItem={(item, index)=>showPost(item, index)}
                    ListFooterComponent={FootForFeed}
                    onEndReachedThreshold={0.3}
                    onEndReached={callMorePosts}
                    keyExtractor={(item)=>item.id}
                    ListFooterComponentStyle={{
                        width: "100%",
                        alignItems: "center",
                        justifyContent: "center",
                        alignContent: "center"
                    }}
                />
            </ImageBackground>
            
        </SafeAreaView>
    );
}
export { Feed };

底部 Post.js

import React from 'react';
import {View, Image, Text, StyleSheet, TouchableOpacity} from 'react-native';
import { uni } from '../css/uni.js';
import { AntDesign, FontAwesome5, Entypo, MaterialIcons, Feather } from '@expo/vector-icons'; 
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import base64 from 'react-native-base64';

function likeOrDislike(postId, navigation){
    AsyncStorage.getItem("mail")
    .then((email)=>{
        if (email == null){
            navigation.replace("Login");
        }else{
            AsyncStorage.getItem("pass")
            .then((passw)=>{
                if (passw == null){
                    navigation.replace("Login");
                }else{
                    axios({
                        method: 'post',
                        url: uni.bind('like'),
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        data: uni.string({
                          mail: email,
                          pass: base64.encode(passw),
                          post: postId
                        })
                      })
                      .then(
                          (response)=>{
                              if (response.status == 200){
                                  let resp = response.data;
                                if (uni.logic(resp) === "true"){
                                    let someVariable = "";
                                }else if (uni.logic(resp) === "error"){
                                    uni.Error();
                                    // alert(resp);
                                }else if (uni.logic(resp) === "invalid"){
                                    navigation.replace("Login");
                                }else{
                                    // uni.Error();  
                                    alert(resp);  
                                }
                              }else{
                                  uni.Error();
                              }
                          }
                      )
                      .catch((e)=>{
                        uni.Error();
                        // alert(e);
                      });
                }
            })
            .catch(()=>{
                uni.Error();
            });
        }
    })
    .catch(()=>uni.Error());
}

function BottomPost(obj){
    const iconDesign = StyleSheet.create({
        icon: {
            margin: 10
        }
    });
    const iconDynamicSizing = 25;
    return(
        <>
          <View style={{
              flexDirection: "row",
              paddingLeft: 10,
              marginTop: 15
          }}>
              <TouchableOpacity onPress={()=>{obj.update.like();likeOrDislike(obj.Post, obj.nav)}}><AntDesign name={obj.liked===true ? "heart" :"hearto"} size={iconDynamicSizing} color="black" style={iconDesign.icon} /></TouchableOpacity>
              <TouchableOpacity><FontAwesome5 name="comment" size={iconDynamicSizing} color="black" style={iconDesign.icon} /></TouchableOpacity>
              <TouchableOpacity><Feather name="send" size={iconDynamicSizing} color="black" style={iconDesign.icon} /></TouchableOpacity>
              <TouchableOpacity><AntDesign name="retweet" size={iconDynamicSizing} color="black" style={iconDesign.icon} /></TouchableOpacity>
            </View>
            <Text style={{marginLeft:20}}>{obj.fav} Likes</Text>
            <Text>{String(obj.liked)}</Text>

        </>
    );
}
export {BottomPost};

0 个答案:

没有答案