How to pass state of one component to another in r

2019-06-02 16:57发布

问题:

I am working on react native and I have two files in first I run geolocation function to get the coordinates and assign it to states. Now I want to access this state in my 2nd file. I tried using props but it shows undefined when I console log. Please help I am a newbie.

export default class MapScreen extends React.Component {

constructor(props) {
super(props);
this.state = {
  mapInitialRegion: {
    latitude: 10,
    longitude: 7,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA
  },
  markers: []
};

this.itemsRef = firebase.database().ref("incidents");
}
componentDidMount() {
// Get Marker Information from the server
//this._getMarkerInformation();
this.listenForItems(this.itemsRef);
// Get user's location to render the map around the user
navigator.geolocation.getCurrentPosition(
  position => {
    lat = parseFloat(position.coords.latitude);
    long = parseFloat(position.coords.longitude);
    console.log(position);
    var initalRegion = {
      latitude: lat,
      longitude: long,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA
    };

    this.setState({ mapInitialRegion: initalRegion });
  },

  //error => alert(error),
);

} .. ..

inside Hospitals.js

import React, { Component } from 'react';
import {
Text,
View,
FlatList,
ActivityIndicator,
AppRegistry
} from 'react-native';

import { Components } from "expo";

import { List, ListItem } from "react-native-elements";

var _ = require('lodash');

export default class Hospitals extends React.Component {
constructor() {
super();

this.state = {
  loading: false,
  data: [],
  pageToken: '',
  refreshing: false,
  siteTitle: ''
};
}
componentDidMount() {
this.fetchData();
}

fetchData = (props) => {

var latitude = this.props.propsname;
var longitude =  this.props.propsname2;
const { pageToken } = this.state;
const urlFirst = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=500&type=hospital&key=your_api_key`
const urlNext = 
`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=500&type=hospital&key=Your_api_key&pagetoken=${pageToken}`;

let url = pageToken === '' ? urlFirst : urlNext
console.log(url);
console.log(latitude);
console.log(longitude);

回答1:

After setting the state inside your MapScreen Component , You need to make sure to pass it as a props to your Hospital Component

So inside your MapScreen you need to import the Hospital component like (you can amend the link accordingly) :

import View from '../components/Hospital'

Inside your MapScreen create a render function and pass state as a props to it (You can amend it accordingly , depending on which props you want to send down to the Hospital )

export default class MapScreen extends React.Component { 

    render() {
        return (<div>< Hospital view={this.state.mapInitialRegion}/></div>)
    }
}

UPDATED :

For checking if this.state is not empty or undefined you can do something like :

export default class MapScreen extends React.Component { 

 let mapInitial;

 if(this.state.mapIntialRegion) {

   mapInitial = < Hospital view={this.state.mapInitialRegion}/>
    } else { mapInitial = <div>Loading ...</div>
     }

    render() {
        return (<div>{mapInitial}</div>)
    }
}

Now inside your Hospital Component you can access the Props via the object you passed inside your MapScreeen render function in this case I have passed view :

this.props.view.mapInitialRegion

or You can make use of destructing like :

const { latitude , longitude} = this.props.view.mapInitialRegion