如何在本机中将一个组件的状态传递给另一个组件? [英] How to pass state of one component to another in react native?

查看:72
本文介绍了如何在本机中将一个组件的状态传递给另一个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

在设置MapScreen组件内部的状态之后,需要确保将其作为道具传递给Hospital组件

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

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

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

import View from '../components/Hospital'

MapScreen内部创建一个渲染函数并将状态作为道具传递(您可以相应地对其进行修改,具体取决于您要向下发送到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>)
    }
}

已更新:

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

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

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

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

或者您可以利用破坏:

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

这篇关于如何在本机中将一个组件的状态传递给另一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆