React Native ERROR: попытка назначить свойство только для чтения, необработанное отклонение обещания - PullRequest
0 голосов
/ 16 июня 2020

Я впервые использую stackoverflow. Мне очень нужно решить эту проблему, я не могу решить ее уже 2 недели. Я обработал все остальные «экраны» своего приложения, но на этом экране просто беспорядок. Было еще 20 ошибок, но мне удалось их решить, но дальше я не могу. Итак, я использую Firebase Firestore, и там у меня есть две коллекции: сообщения и пользователи. В основном я звоню сообщениям, и они иногда появляются, и все в порядке, и иногда я получаю эту ошибку, поэтому она вылетает. Пожалуйста, помогите. Я даже могу заплатить за помощь, мне это действительно нужно ... это мой код:

import React from "react";
import { View, Text, StyleSheet, Image, FlatList, ActivityIndicator, 
TouchableOpacity, StatusBar, RefreshControl } from "react-native";
import { Ionicons,  } from "@expo/vector-icons";
import moment from "moment";
import { FontAwesome5 } from "@expo/vector-icons";
//import CachedImage from 'react-native-expo-cached-image';
import { DrawerActions } from "react-navigation-drawer";
import { ClassicHeader } from "@freakycoder/react-native-header-view";
import 'firebase/firestore';  //import * as firebase from 'firebase'; 
import '@firebase/firestore';  //import 'firebase/firestore'; //require("firebase/firestore");
import Fire from "../Fire";
require("firebase/firestore");

export default class HomeScreen extends React.PureComponent {
    constructor(props) {
        super(props);
        isMounted = false;

        this.state = {
        loading: false, // user list loading
        isRefreshing: false, //for pull to refresh
        post: [],
        user: {},
        error: ''
    }; }

    componentDidMount() {
        this.searchPosts();
        this.isMounted=true;
      }

      componentWillUnmount() {
        this.isMounted=false;
    }

    onRefresh() {
        this.setState({ isRefreshing: true }, function() { this.searchPosts() });
     }

     searchPosts = async (page) => {

            this.isMounted = true;
            const db = Fire.shared.firestore;  //same for me as const db = firebase.firestore
            const ref = await db.collection("posts").get().then((querySnapshot => {
                const data = querySnapshot.docs.map(doc => ({...doc.data(), key: doc.id }));
                this.setState({ post : data, loading: false })
                })).catch(error => {
                        this.setState({ loading: false, error: 'Loading did not succeed.' })
                      }); 

                    //const user = Fire.shared.uid;
                    const refer = await db.collection("users").get().then((querySnapshot => {
                        const data2 = querySnapshot.docs.map(doc => ({...doc.data(), key: doc.id }));
                        this.setState({ user : data2, loading: false});
                            })).catch(error => {
                                this.setState({ loading: false, error: 'Loading did not succeed.' })
                              });


                        const user = Fire.shared.uid;
                        this.isMounted = Fire.shared.firestore
                        .collection("users")
                        .doc(user)
                        .onSnapshot(doc => {
                this.setState({ user: doc.data() });
            });   
            }


                        renderSeparator = () => {
                            return (
                              <View
                                style={{
                                  height: 2,
                                  width: '100%',
                                  backgroundColor: '#CED0CE'
                                }}
                              />
                            );
                          };


                          renderFooter = () => {
                            //it will show indicator at the bottom of the list when 
                            //data is loading otherwise it returns null
                             if (!this.state.loading) return null;
                             return (
                               <ActivityIndicator
                                 style={{ color: '#000' }}
                               />
                             );
                           };


                           handleLoadMore = () => {
                            if (!this.state.loading) {
                              this.page = this.page + 1; // increase page by 1
                              this.searchPosts(this.page); // method for API call 
                            }
                          };



    renderPost = (post) => {
        return (
            <View style={styles.feedItem}> 
                <Image 
                source={
                        this.state.user.avatar
                        ? { uri: this.state.user.avatar }
                        : require("../assets/tempAvatar.jpg")
                            }
                style={styles.avatar} />
                <View style={{ flex: 1 }}>
                    <View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
                        <View>
                            <Text style={styles.name}>{post.name}</Text>
                            <Text style={styles.timestamp}> 
                {moment(post.timestamp).toDate().toDateString()}</Text>
                        </View>

                        <Ionicons name="ios-more" size={24} color="#73788B" />
                    </View>
                    <Text style={styles.post}>{post.text}</Text>
                    <Image source={post.image && { uri: post.image}} style={styles.postImage} resizeMode="cover" />
                    <View style={{ flexDirection: "row" }}>
                        <Ionicons name="ios-heart-empty" size={24} color="#73788B" style={{ marginRight: 16 }} />
                        <Ionicons name="ios-chatboxes" size={24} color="#73788B" />
                    </View>
                </View>
            </View>
        );
    };

    render() {
        if (this.state.loading && this.page === 1) {
            return <View style={{
              width: '100%',
              height: '100%'
            }}><ActivityIndicator style={{ color: '#000' }} /></View>;
          }


        return (
            <View style={styles.container}>
            <StatusBar translucent backgroundColor="white" barStyle="dark-content" /> 
            <ClassicHeader
            headerTitle="Eleph"
            leftComponent={
    <TouchableOpacity 
    style={{  marginRight:0, margin: 10 }}
    onPress={() => this.props.navigation.dispatch(DrawerActions.openDrawer())}>
<FontAwesome5 name="bars" size={24} color="#161924" />
</TouchableOpacity> }
  rightComponent={
    <TouchableOpacity 
    style={{  marginLeft:0, margin: 10 }}
    onPress={() => this.props.navigation.navigate("Message")} >
<Ionicons name="ios-chatboxes" size={24} color="#73788B" />    
</TouchableOpacity>
  } />
            <FlatList
                    style={styles.feed}
                    data={this.state.post}
                    renderItem={({ item }) => 
                    this.renderPost(item)
                    }
                    refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this.onRefresh.bind(this)}
            />
          }
                    keyExtractor={(item, index) => String(index)}
                    //ItemSeparatorComponent={this.renderSeparator}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReachedThreshold={0.4}
                    onEndReached={this.handleLoadMore.bind(this)}
                    showsVerticalScrollIndicator={false}
                ></FlatList>
            </View>
        );
    }
}

введите описание изображения здесь введите описание изображения здесь

...