2017-02-15 14 views
0

ジオロケーションを取得しようとしていますが、setstateを子コンポーネントに渡しています。問題は、ジオロケーションが状態に設定される前に、状態を必要とするコンポーネントがレンダリングされることです。私は、状態が変わると、Reactはその状態を使用するコンポーネントを再レンダリングすると考えました。反応中の親から子へのジオロケーションを渡す

class App extends Component { 
 
\t constructor(props) { 
 
\t \t super(props) 
 
\t \t this.state = { 
 
\t \t \t location: null, 
 
\t \t \t venues: [], 
 
\t \t \t markers: [] 
 
\t \t } 
 
\t \t this.getCurrentLocation = this.getCurrentLocation.bind(this) 
 
\t \t this.setCurrentLocation = this.setCurrentLocation.bind(this) \t \t 
 
\t } 
 
    
 
     setCurrentLocation(currentLocation) { 
 
\t \t this.setState({location: currentLocation})  \t \t 
 
\t } 
 

 
\t getCurrentLocation() { 
 
\t \t let self = this; \t 
 
\t \t navigator.geolocation.getCurrentPosition(function(position) { \t \t \t \t \t 
 
\t \t \t let updatedLocation = { 
 
\t \t \t \t lat: position.coords.latitude, 
 
\t \t \t \t lng: position.coords.longitude 
 
\t \t \t } 
 
\t \t \t self.setCurrentLocation(updatedLocation) \t \t \t 
 
\t \t }) 
 
\t } 
 
    
 
     render() { 
 
\t \t const markers = [ 
 
\t \t \t { 
 
\t \t \t \t location: { 
 
\t \t \t \t \t lat: this.state.location.lat, 
 
\t \t \t \t \t lng: this.state.location.lng 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t ] 
 
\t \t return (
 
\t \t \t <div className="main-container"> 
 
\t \t \t \t <h1>Render a Map</h1> 
 
\t \t \t \t <div className="inner-container"> 
 
\t \t \t \t \t <div className="map"> 
 
\t \t \t \t \t \t <Map center={this.state.location} markers={markers}/> 
 
\t \t \t \t \t </div> 
 
\t \t \t \t \t 
 
\t \t \t \t </div> 
 
\t \t \t </div> 
 
\t \t) 
 
\t } 
 
}

これは、場所にあなたの助けのための

class Map extends Component { 
 
\t constructor(props) { 
 
\t \t super(props) \t \t 
 
\t } 
 

 
\t render() { \t \t 
 
\t \t const mapContainer = <div className="map-container"></div> 
 
\t \t const markers = this.props.markers.map((marker, i) => { 
 
\t \t \t const place = { 
 
\t \t \t \t position: { 
 
\t \t \t \t \t lat: marker.location.lat, 
 
\t \t \t \t \t lng: marker.location.lng 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t \t return <Marker key={i} {...place} /> 
 
\t \t }) 
 
\t \t return (
 
\t \t \t <GoogleMapLoader 
 
\t \t \t \t containerElement={mapContainer} 
 
\t \t \t \t googleMapElement={ 
 
\t \t \t \t \t <GoogleMap 
 
\t \t \t \t \t \t defaultZoom={15} 
 
\t \t \t \t \t \t defaultCenter={this.props.center} 
 
\t \t \t \t \t \t options={{streetViewController: false, mapTypeControl: false}}> 
 
\t \t \t \t \t \t { markers } 
 
\t \t \t \t \t </GoogleMap> 
 
\t \t \t \t } /> 
 
\t \t) 
 
\t } 
 
}

感謝を使用するコンポーネントです。

答えて

0

データがあるまで子をレンダリングしないでください。

{this.state.location && <Map .../>}

は言われていること、Mapコンポーネントは、その小道具が変わるたびに再レンダリングする必要があり、私はあなたがそれが予想される場合location状態が実際に変化しているリアクトDEV-ツールでチェックしたいです。

+0

釘付け、ありがとう! –

関連する問題