平板列表未在React Native中更新

时间:2019-05-16 07:54:11

标签: android react-native updates react-native-flatlist

我想在获取Firebase后更新我的单位列表。但是下面我的代码没有更新。我正在从Firebase提取数据并放入数组中。当我调用该数组时,没有找到数据。我怎样才能解决这个问题?我知道这段代码很愚蠢。但是请帮忙...

从'react'导入React;           从'react-native'导入{StyleSheet,Text,View,StatusBar,Image,ScrollView,TouchableOpacity,SafeAreaView,TextInput};

      import * as firebase from "firebase";
      import Geolocation from "react-native-geolocation-service";
      import geolib from "geolib";
      import Permissions from "react-native-permissions";
      import Share from "react-native-share";
      import RNFetchBlob from "react-native-fetch-blob";
      let base_64;

      //===================card view========================
      var data = [];
      var data1 = [];
      var i = 0;
      let coordsLat;
      let coordslon;
      let Geoposition = 0;

      let dist1;
      let geolat = 51.525;
      let geolon = 51.525;
      Number(geolat);
      Number(geolon);
      const formatData = (data, numColumns) => {
        const numberOfFullRows = Math.floor(data.length / numColumns);

        let numberOfElementsLastRow = data.length - numberOfFullRows * numColumns;
        while (
          numberOfElementsLastRow !== numColumns &&
          numberOfElementsLastRow !== 0
        ) {
          data.push({ key: `blank-${numberOfElementsLastRow}`, empty: true });
          numberOfElementsLastRow++;
        }

        return data;
      };

      const numColumns = 4;
      //====================================================
      var itm = [];
      var arr =[

          'https://firebasestorage.googleapis.com/v0/b/taam-623b6.appspot.com/o/Circles%2FGroup-615.png?alt=media&token=23e9c5dc-16f3-426e-b1ce-68c35fd145b2',
          'https://firebasestorage.googleapis.com/v0/b/taam-623b6.appspot.com/o/Circles%2Fgroupgre.png?alt=media&token=5a280580-8c4b-4aef-83c4-4626174b04fa',
          'https://firebasestorage.googleapis.com/v0/b/taam-623b6.appspot.com/o/Circles%2Folivegreen.png?alt=media&token=dc72ce64-e794-4aab-a0a9-54f134d0d5dd',
          'https://firebasestorage.googleapis.com/v0/b/taam-623b6.appspot.com/o/Circles%2Forange.png?alt=media&token=4631ff27-26d6-4d19-9370-40893d15af8f',
          'https://firebasestorage.googleapis.com/v0/b/taam-623b6.appspot.com/o/Circles%2Fteal.png?alt=media&token=7522aea2-02c4-4f13-9cb4-e7d43ce684e9',
          'https://firebasestorage.googleapis.com/v0/b/taam-623b6.appspot.com/o/Circles%2Fyellow.png?alt=media&token=6375fd68-fd93-40b8-a989-aef0e96e10ff'
        ];
        var value;
        let items = [];
      export default class temp extends React.Component {

        constructor(props) {
          super(props);

          this.state = {
            items: [],
            calltimer: true,
            search: "",
            loadsearchresult: false, //not used yet
            update: "",
            locationPermission: "",
            datalist:[]
          };
        }
        componentWillMount() {
          Permissions.check("location").then(response => {
            // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
            this.setState({ locationPermission: response });
          });

          //this.geolocation();
          this.fetchData();

        }

        fetchData = async () => {

          var i=0;
          let stop=false;
          this.setState({ loading: true });
          console.log("savad");
          //========================================
          firebase
            .database()
            .ref("/Brands/")
            .on("value", snap => {

                //-------------------------------------------

                snap.forEach(brand =>{
                    stop=false;

                    firebase.database().ref("/flyers/").on("value", snap=>{
                          snap.forEach(flyer =>{
                              if(stop==false){

                          if (brand.val().Name=== flyer.val().BrandName){

                //////////////////////////////////////////////////////////////////
                Geolocation.getCurrentPosition(position => {

                    geolat = flyer.val().latitutde;
                    geolon = flyer.val().longitude;
                    dist1 =
                      geolib.getDistance(position.coords, {
                        latitude: geolat,
                        longitude: geolon
                      }) / 1000;
                      if (dist1 < 50000) {
                          items.push({

                                      Name:brand.val().Name,
                                      ImageUrl:brand.val().ImageUrl,
                                      Circle:value = arr[Math.floor(Math.random() * arr.length)]
                                      })
                                  //stop=true;

                                  data=items;

                                  this.setState({datalist:items})
                                  alert(JSON.stringify(items))


                      }

                });
                /////////////////////////////////////////////////////////////////

                          }

                          }
                          })
                    })






                  //----------------------------------------------



                })


              itm = items;

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


            });

            this.setState({update:' '})
          //=========================================
        };
        //=======================================================

        //-------------------------------logout----------------------------------
        logout() {
          Alert.alert("Logout", "Do You Want to Logout", [
            {
              text: "Cancel",
              onPress: () => {},
              style: "cancel"
            },
            {
              text: "OK",
              onPress: () => {
                AsyncStorage.removeItem("user");
                this.props.navigation.navigate("Login");
              }
            }
          ]);
        }

        //===========================card view=====================
        renderItem = ({ item, index }) => {
          if (item.empty === true) {
            return <View style={[styles.item, styles.itemInvisible]} />;
          }
          {

          }


          return (
            <View key={index} style={styles.item}>

              <View key={index} style={styles.imagecontainer}>

                <TouchableNativeFeedback
                  onPress={() =>
                    this.props.navigation.navigate("FlyerListing1", {
                      PassedName: item.Name,
                      //PassedCircleUrl:item.Circle,
                      PassedImageUrl:item.ImageUrl,
                      Paramnav: "FlyersNearBy"
                    })
                  }
                >
                <View style={{ width: "90%", height: "70%", marginTop:"25%", marginLeft:15, borderRadius: 100}}>
                  <ImageBackground
                    key={index}
                    style={{ width: "90%", height: "90%", marginTop:"25%" }}
                    source={{ uri:item.Circle}}

                  >

                {/* ------------SocialMediaShare------------------ */}

                  <View  style={{ width: "50%", height: "50%", marginLeft:"22%", marginTop:"25%"}}>
                  <Image
                    key={index}
                    style={{ width: "90%", height:"90%",resizeMode:"contain",justifyContent:'center',alignItems:'center'}}
                    source={{uri:item.ImageUrl}}
                  />

                  </View>
                  {/* ------------------------------------------ */}
                  </ImageBackground></View>
                </TouchableNativeFeedback>

              </View>
              <View style={{marginLeft:-1,marginTop:-5,alignItems: 'center', justifyContent: 'center',}}>
              <Text key={index} style={styles.itemText}>
              {item.Name}
              </Text>
              </View>
            </View>
          );
        };

        //=========================================================




        render() {

          {this.state.update}
          return (
            <SafeAreaView style={styles.first}>
            <View style={styles.second}>

              <StatusBar hidden />
              <View Style={styles.third}>
              </View>
              <View style={styles.fourth}>
              <TouchableOpacity>
                    <Image
                      style={styles.fifth}
                      source={require("../src/Assets/Icons/drawable-xxxhdpi/Path_375.png")}
                    />
                  </TouchableOpacity>
                <View>
                <Image style={styles.sixth} source={require('../src/Assets/logo.png')} />
                </View>
                <TouchableOpacity onPress={() => this.logout()}>
                    <Image
                      style={styles.fifth1}
                      source={require("../src/Assets/Icons/drawable-xxxhdpi/logout.png")}
                    />
                  </TouchableOpacity>
              </View>

              <ScrollView vertical={true} style={styles.container}>

              <View style={styles.seventh}>
                  <View style={styles.eighth}>
                    <TouchableOpacity style={styles.ninth}>
                      <Image
                        style={styles.eleventh}
                        source={require("../src/Assets/Search.png")}
                      />
                    </TouchableOpacity>
                    <View style={styles.twelth}>
                      <TouchableOpacity
                        onPress={() =>
                          this.props.navigation.navigate("Search", {
                            Paramnav: "FlyersNearBy"
                          })
                        }
                      >
                        <TextInput
                          underlineColorAndroid="transparent"
                          placeholder="Search                               "
                          onChangeText={search => this.setState({ search })}
                          onFocus={() =>
                            this.props.navigation.navigate("Search", {
                              Paramnav: "FlyersNearBy"
                            })
                          }
                        />
                      </TouchableOpacity>
                    </View>

                  </View>

                </View>

                <View style={styles.seventeenth}>
                    <TouchableOpacity style={styles.eighteenth} onPress={() => this.props.navigation.navigate("SuperMarket1")}>
                    <Image style={styles.ninteenth}source={require('../src/Assets/Group256.png')} />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.twenty}>
                    <Image style={styles.twenty1} source={require('../src/Assets/Group257.png')} />

                    </TouchableOpacity>
                </View>
                <View style={styles.twenty2}>
                <Image style={styles.twenty3}source={require('../src/Assets/PageTitle-3.png')} />
                </View>
                <FlatList
                    data={formatData(data, numColumns)} //data={formatData(data, numColumns)}
                    style={styles.container1}
                    renderItem={this.renderItem}
                    numColumns={numColumns}
                  />

              </ScrollView>
              <View style={styles.thirty4}>
                    <TouchableOpacity>
                      <Image style={styles.part} source={require('../src/Assets/home-button.png')} />
                    </TouchableOpacity>

                  </View>
            </View>
            </SafeAreaView>
          );
        }
      }

1 个答案:

答案 0 :(得分:0)

您通过在数组实例上调用push直接改变状态。因此,渲染功能不会在更改状态时进行更新(重新渲染)。确保您没有改变状态