TypeError: undefined is not an object ( evaluating 'this.state.locInfo[index].Images.split')

Viewed 397

When I click the map in React-native, I am trying to redirect. But I'm getting an error. mapview.js => I'm redirecting ShowInfo.js.

The code I'm redirecting to:

ShowInfo.js

Actions.ShowInfo({ rating: this.props.rating, locID: this.props.locID, images: this.state.imgLink, tourName: this.props.name, info: this.props.info }) // The Code I'm Redirecting

enter image description here

Mapview.js Code Text

import React from 'react';
//import {View, Text} from 'react-native';
import { getDistance, getPreciseDistance } from 'geolib';
import MapView, { Marker, PROVIDER_GOOGLE, Callout } from 'react-native-maps';
import Geolocation from '@react-native-community/geolocation';
import { Actions } from 'react-native-router-flux';

import {
  StyleSheet,
  Image,
  View,
  Dimensions,
  TouchableOpacity,
  Text,
} from 'react-native';
const { width, height } = Dimensions.get('window');
import LinearGradient from 'react-native-linear-gradient';
import MapViewDirections from 'react-native-maps-directions';
import ImagePicker from 'react-native-image-picker';




export default class Mapview extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      latitude: 0,
      longitude: 0,
      error: null,
      coords: [],
      places: null,
      selectedLat: "",
      selectedLang: "",
      distance: "",
      tourStatus: false,
    };
  }
  getLocation = () => {
    Geolocation.getCurrentPosition(position => {
      this.setState({ latitude: position.coords.latitude })
      this.setState({ longitude: position.coords.longitude })
    }
    );
  }

  setLatLang = (lat, lng) => {
    this.setState({ selectedLat: lat })
    this.setState({ selectedLang: lng })
  }

  showCoords() {
    const arrayMarkers = [];
    var coordsLatLang = [];
    var allCoords = [];
    var selectedCoordLat = [];
    var selectedCoordLang = [];
    var dis = [];

    Geolocation.getCurrentPosition(position => {
      var userLat = position.coords.latitude
      var userLang = position.coords.longitude

      for (let index = 0; index < this.props.locCoord.length; index++) {
        coordsLatLang = this.props.locCoord[index].split(',')
        allCoords.push(this.props.locCoord[index].split(','))
        selectedCoordLat.push(allCoords[index][0])
        selectedCoordLang.push(allCoords[index][1])
        dis.push(getDistance(
          { latitude: userLat, longitude: userLang },
          { latitude: selectedCoordLat[index], longitude: selectedCoordLang[index] }
        ))

        var lat = coordsLatLang[0]
        var lng = coordsLatLang[1]

        arrayMarkers.push(
          < Marker
            pinColor={'#24012f'}
            coordinate={{
              latitude: Number(lat),
              longitude: Number(lng),
            }}
          >
          
            <Callout tooltip style={{ position: 'relative' }} onPress={() => {

              Actions.ShowInfo({ rating: this.props.rating, locID: this.props.locID, images: this.state.imgLink, tourName: this.props.name, info: this.props.info }) // The Code I'm Redirecting
              
            }} >
              <LinearGradient start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{ borderRadius: 20 }} colors={['#531c5c', '#4b5cab']}>
                <View style={{ flexDirection: 'column', alignContent: 'center', alignItems: 'center', flex: 1, padding: 15 }}>
                  <Text style={{ color: "white", fontWeight: 'bold', fontSize: 20 }}>{this.props.locNames[index]}</Text>
                  <Text style={{ marginTop: 5, color: "white" }}>Puanı:{this.props.TourLocRating[index].toFixed(2)}</Text>
                  <Text style={{ color: "white" }}>Mesafe:{(dis[index] / 1000).toFixed(2)}KM</Text>
                  <Text style={{ marginTop: 5, color: "white", marginBottom: 5 }}>Rota Oluşturmak İçin Tıklayın!</Text>
                </View>
              </LinearGradient>
            </Callout>
          </Marker >
        )
      }
    }
    )

    this.setState({ places: arrayMarkers })
  }


  openCam() {
    ImagePicker.launchCamera((response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        const source = { uri: response.uri };

        // You can also display the image using data:
        // const source = { uri: 'data:image/jpeg;base64,' + response.data };

        this.setState({
          avatarSource: source,
        });
      }
    });
  }

  componentWillMount() {
    this.showCoords();
  }

  componentDidMount() {
    this.getLocation();
  }


  render() {
    console.log(this.props.images)
    return (
      <View style={{ flex: 1 }}>
        <View style={{
          backgroundColor: 'white',
          alignItems: 'center',
          width: width,
          height: height * 0.08,
          fontWeight: "bold",
          flexDirection: 'row',
          justifyContent: 'flex-start',
        }}>
          <TouchableOpacity onPress={() => { this.props.navigation.goBack() }}>
            <Image
              style={{ width: width * 0.05, height: height * 0.03, marginTop: 15, marginBottom: 10, marginLeft: 5 }}
              source={require('../../img/back.png')}
            />
          </TouchableOpacity>
          <Image resizeMode="contain" style={{ marginLeft: width * 0.17 }}
            source={require('../../img/headerText.png')}
          />
        </View>
        <View style={[styles.lineFooterStyle]} />
        <MapView
          provider={PROVIDER_GOOGLE}
          region={{
            latitude: this.state.latitude,
            longitude: this.state.longitude,
            latitudeDelta: 0.0922,
            longitudeDelta: 0.0421,
          }}
          showsUserLocation={true}
          style={{ flex: 1 }}
        >
          {this.state.places}

          <MapViewDirections
            precision={"high"}
            origin={{ latitude: this.state.latitude, longitude: this.state.longitude }}
            destination={{ latitude: this.state.selectedLat, longitude: this.state.selectedLang }}
            apikey={'AIzaSyAYGO8DoGtW-v8lEdDbtagGNp5ogtAA8ok'}
            strokeWidth={6}
            strokeColor="#531959"
          />
        </MapView>
        <View>

          <TouchableOpacity style={{ width: width * 0.2, height: width * 0.2, marginTop: -height * 0.17, marginLeft: width * 0.4 }} onPress={() => this.openCam()}>
            <Image style={{ width: width * 0.2, height: width * 0.2, marginTop: 15, borderRadius: 25 }}
              source={require('../../img/ARLogo.png')}
            />
          </TouchableOpacity>
        </View>

        <View style={styles.lineFooterStyle} />
        <View style={styles.footerStyle}>
          <TouchableOpacity style={styles.styleInBottombar} onPress={() => this.props.navigation.navigate("Mainpage")}>
            <Image style={styles.navItemHomeStyle}
              source={require('../../img/Home.png')}
            />
          </TouchableOpacity>
          <TouchableOpacity style={styles.styleInBottombar} onPress={() => this.props.navigation.navigate("Discover")}>
            <Image style={styles.navItemBookmarkStyle}
              source={require('../../img/Bookmark_2.png')}
            />
          </TouchableOpacity>
          <TouchableOpacity style={styles.styleInBottombar} onPress={() => this.props.navigation.navigate("MyProfile")}>
            <Image style={styles.navItemProfileStyle}
              source={require('../../img/Profile.png')}
            />
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

ShowInfo.js Code Text

import React from 'react';
import { Actions } from 'react-native-router-flux';
import {
    StyleSheet,
    Text,
    ScrollView,
    Image,
    View,
    Dimensions,
    TouchableOpacity,
    TextInput
} from 'react-native';

import { AirbnbRating, Rating } from 'react-native-ratings';
import LinearGradient from 'react-native-linear-gradient';
import * as firebase from 'firebase';
import { SliderBox } from "react-native-image-slider-box";
const { width, height } = Dimensions.get('window');
import Comment from '../HorizontalSlider/Comment';
let userRef = db.ref('/Users');
let commentsRef = db.ref('/LocationComments');
let locationRef = db.ref('/Location');
import { db } from '../../components/dbConfig/config';
if (!firebase.apps.length) {
    firebase.initializeApp(db);
}

const rootRef = firebase.database().ref();
const loccommentRef = rootRef.child('LocationComments');

let addItem = (comment, locationID, userName, rating, comments, locID) => {
    loccommentRef.push({
        comment: comment,
        LocationID: locationID,
        username: userName,
        users: [],
        rating: rating
    });
    var count = 0;
    var newRating = 0;
    for (let index = 0; index < comments.length; index++) {
        if (locID == comments[index].LocationID) {
            count++;
            newRating += comments[index].rating
        }
    }
    var generalNewRating = (newRating + rating - 1) / count
    locationRef.child(locID).update({ 'Rating': generalNewRating })
};

export default class ShowInfo extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            locInfo: [],
            comments: [],
            comment: '',
            userName: '',
            userEmail: '',
            rating: '',
            users: [],
        };
    }

    ratingCompleted = (rating) => {
        this.setState({ rating: rating })
    }

    getUserData() {
        userRef.on('value', snapshot => {
            let data = snapshot.val();
            let users = Object.values(data);
            this.setState({ users: users });
        });
    }

    getComments() {
        commentsRef.on('value', snapshot => {
            let data = snapshot.val();
            let comments = Object.values(data);
            this.setState({ comments: comments });
        });
    }

    getLocationData() {
        locationRef.on('value', snapshot => {
            let data = snapshot.val();
            let locInfo = Object.values(data);
            this.setState({ locInfo: locInfo });
        });
    }

    getUserName = () => {
        for (let index = 0; index < this.state.users.length; index++) {
            if (this.props.userEmail == this.state.users[index].email) {
                return this.state.users[index].username;
            }
        }
    }
    updateRating = () => {
        var count = 0;
        for (let index = 0; index < this.state.comments.length; index++) {
            if (this.props.locID == this.state.comments[index].LocationID) {
                count++;
            }
        }
        locationRef.child(this.props.locID).update({ 'Rating': (this.state.locInfo[this.props.locID].Rating + this.state.rating) / count })
    }


    componentWillMount() {
        this.getLocationData()
        this.getUserData()
        this.getComments()
    }
    inRender(images, commentContext, comments, locCoord, locNames) {

        console.log(this.state.locInfo[2].Rating, "---")
        if (this.getUserName() != null) {
            this.setState({ userName: this.getUserName() })
        }
        for (let index = 0; index < this.state.locInfo.length; index++) {
            if (this.props.locID == this.state.locInfo[index].ID) {
                images = this.state.locInfo[index].Image.split(',')
                locCoord.push(this.state.locInfo[index].Coordinate)
                console.log(locCoord)
                locNames.push(this.state.locInfo[index].Name)
            }
        }
        for (let index = 0; index < this.state.comments.length; index++) {
            if (this.props.locID == this.state.comments[index].LocationID) {
                comments.push(this.state.comments[index])
            }
        }
        for (let index = 0; index < comments.length; index++) {
            if (comments[index].username != "") {
                commentContext.push(
                    <Comment
                        username={comments[index].username}
                        comment={comments[index].comment}
                        rating={comments[index].rating}
                    />
                )
            }
        }
        return images;
    }
    render() {
        var locNames = [];
        var images = [];
        var comments = [];
        var commentContext = [];
        var locCoord = []
        var retImages = this.inRender(images, commentContext, comments, locCoord, locNames);
        var TourLocRating = [];
        TourLocRating.push(this.props.rating)
        return (
            <View style={{ flex: 1, backgroundColor: 'white' }}>
                <View style={{
                    backgroundColor: 'white',
                    alignItems: 'center',
                    width: width,
                    height: height * 0.08,
                    fontWeight: "bold",
                    flexDirection: 'row',
                    justifyContent: 'flex-start',
                }}>
                    <TouchableOpacity onPress={() => { this.props.navigation.goBack() }}>
                        <Image
                            style={{ width: width * 0.05, height: height * 0.03, marginTop: 15, marginBottom: 10, marginLeft: 5 }}
                            source={require('../../img/back.png')}
                        />
                    </TouchableOpacity>
                    <Image resizeMode="contain" style={{ marginLeft: width * 0.17 }}
                        source={require('../../img/headerText.png')}
                    />
                </View>
                <View style={[styles.lineFooterStyle]} />
                <ScrollView>
                    <SliderBox
                        style={{ height: height * 0.4, marginLeft: 5, marginRight: 5 }}
                        imageLoadingColor="white"
                        dotColor="white"
                        inactiveDotColor="#90A4AE"
                        autoplay
                        disableOnPress
                        circleLoop
                        images={retImages}
                    //currentImageEmitter={index => locName=imgSliderHolder[index].Name} //Resim üzerinde lokasyonun adını gösterebilirsin. Resim geldiğinde gerçekleşen func. 
                    //onCurrentImagePressed={index => Actions.ShowInfo({ locImage: images[index], tourName: imgSliderHolder[index].Name, info: imgSliderHolder[index].Info })}
                    />
                    <View style={{ marginLeft: 15 }}>
                        <View style={{ flexDirection: 'row' }}>
                            <View style={{ flexDirection: 'column' }}>
                                <View style={{ marginTop: 30 }}>
                                    <Text style={{ color: '#171c69', fontWeight: 'bold', fontSize: 15, marginLeft: height * 0.01 }}>{this.props.tourName}</Text>
                                    <LinearGradient style={styles.gradientLineStyle} start={{ x: 0, y: 1 }} end={{ x: 1, y: 1 }} colors={['#3E276F', '#F9F7F6']}></LinearGradient>
                                </View>
                                <TouchableOpacity style={styles.BtnStyleLogin} onPress={() => Actions.LocMapview({ locCoord: locCoord, locNames, kind: "location", TourLocRating })}>
                                    <Text style={{ color: 'white' }}>
                                        Başla
                                    </Text>
                                </TouchableOpacity>
                                <View style={{ flexDirection: 'row' }}>
                                    <Rating
                                        readonly={true}
                                        startingValue={this.props.rating}
                                        style={{ paddingVertical: 10 }}
                                        imageSize={20}
                                    />
                                    <Text style={{ marginLeft: width * 0.02, marginBottom: height * 0.015, marginTop: height * 0.012, fontWeight: 'bold' }}>Puanı:{this.props.rating.toFixed(2)}</Text>
                                </View>
                            </View>
                            <TouchableOpacity onPress={() => this.playSound()}>
                                <Image style={{ width: 40, height: 40, marginTop: height * 0.1, }}
                                    source={require('../../img/sound_button.png')}
                                />
                            </TouchableOpacity>
                        </View>
                        <View style={{ flexDirection: 'row', marginBottom: 15, marginTop: 15, justifyContent: 'space-between' }}>
                            <TouchableOpacity onPress={() => { this.refs._scrollView.scrollTo(); }}>
                                <Text style={{ color: '#171c69', fontWeight: 'bold', fontSize: 15, marginLeft: height * 0.025 }}>Hakkında</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => { this.refs._scrollView.scrollTo({ x: width, y: 0 }); }}>
                                <Text style={{ color: '#171c69', fontWeight: 'bold', fontSize: 15, marginRight: 15 }}>Değerlendir</Text>
                            </TouchableOpacity>
                        </View>
                        <LinearGradient style={styles.gradientLineStyle} start={{ x: 0, y: 1 }} end={{ x: 1, y: 1 }} colors={['#3E276F', '#F9F7F6']}></LinearGradient>
                    </View>



                    <ScrollView
                        ref='_scrollView'
                        horizontal={true}
                        pagingEnabled={true}
                    >
                        <View style={{
                            flex: 1,
                            width: width,
                        }}>
                            <Text style={{ padding: 15, textAlign: 'justify' }}>{this.props.info}</Text>
                        </View>
                        <View
                            style={{
                                flex: 1,
                                width: width,
                                padding: 15
                            }}>
                            <TextInput
                                style={{ height: 150, borderColor: 'gray', borderWidth: 0.5, borderRadius: 25 }}
                                multiline={true}
                                onChangeText={comment => this.setState({ comment })}
                            />
                            <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
                                <View style={{ marginTop: 20 }}>
                                    <AirbnbRating
                                        count={5}
                                        showRating={false}
                                        onFinishRating={this.ratingCompleted}
                                        defaultRating={0}
                                        size={30}
                                        fractions={2}
                                    />
                                </View>
                                <TouchableOpacity style={{
                                    width: width * 0.3,
                                    height: height * 0.06,
                                    marginTop: 15,
                                    marginBottom: 15,
                                    borderRadius: 15,
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    backgroundColor: '#1a345c',
                                    flexDirection: 'row',
                                }} onPress={() => addItem(this.state.comment, this.props.locID, this.state.userName, this.state.rating, this.state.comments, this.props.locID)}>
                                    <Text style={{ color: 'white' }}>
                                        Değerlendir
                            </Text>
                                </TouchableOpacity>
                            </View>
                            <Text style={{ color: '#171c69', fontWeight: 'bold', fontSize: 25, marginTop: 15 }}>Yorumlar</Text>
                            {commentContext}
                        </View>

                    </ScrollView>

                </ScrollView>
                <View style={styles.lineFooterStyle} />
                <View style={styles.footerStyle}>
                    <TouchableOpacity style={styles.styleInBottombar} onPress={() => this.props.navigation.navigate("Mainpage")}>
                        <Image style={styles.navItemHomeStyle}
                            source={require('../../img/Home.png')}
                        />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.styleInBottombar} onPress={() => this.props.navigation.navigate("Discover")}>
                        <Image style={styles.navItemBookmarkStyle}
                            source={require('../../img/Bookmark_2.png')}
                        />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.styleInBottombar} onPress={() => this.props.navigation.navigate("MyProfile")}>
                        <Image style={styles.navItemProfileStyle}
                            source={require('../../img/Profile.png')}
                        />
                    </TouchableOpacity>
                </View>

            </View>
        );
    }
}
0 Answers
Related