Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

React-native Sending information between pages?

Hello, I want to redirect Mapview.js to ShowInfo.js page. I want to send ** locInfo ** information while redirecting. locInfo is a variable defined in ShowInfo. How can I do this in Mapview.js.

I get an error when I write this code in Mapview.js.

Actions.ShowInfo({locationID: this.props.locID })

My purpose; Location information, pictures descriptions etc. from Mapview.js to ShowInfo. Send.

Mapview.js

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 {
  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: "",
    };
  }

  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={() => this.setLatLang(selectedCoordLat[index], selectedCoordLang[index])}>
              <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={'s-v8lEdDbtagGsssssasaNp5ogtAA8ok'}
            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>
    );
  }
}

ShowInfo.js

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[in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...