如何在 React Native 中将一个组件的状态传递给另一个组件?

IT技术 reactjs google-maps oop react-native
2021-04-30 15:01:07

我正在研究本机react,首先我有两个文件,我运行geolocation函数来获取坐标并将其分配给状态。现在我想在我的第二个文件中访问这个状态。我尝试使用,props但在控制台日志时显示未定义。请帮助我是新手。

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),
);

} .. ..

在 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个回答

在您的MapScreenComponent内设置状态后,您需要确保将其作为props传递给您的HospitalComponent

因此,您MapScreen需要在内部导入 Hospital 组件(您可以相应地修改链接):

import View from '../components/Hospital'

在您MapScreen创建一个渲染函数并将状态作为props传递给它(您可以相应地修改它,具体取决于您要发送到 的propsHospital

export default class MapScreen extends React.Component { 

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

更新 :

检查this.state is not empty or undefined您是否可以执行以下操作:

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>)
    }
}

现在在你的Hospital组件中,你可以通过你在MapScreeen渲染函数中传递的对象访问props,在这种情况下我已经传递了view

this.props.view.mapInitialRegion

或者你可以使用像这样的破坏:

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