2017-02-23 46 views
0

我有一個組件A陣營獲得的子組件道具內部函數使用

import React, { Component } from 'react' 
import Gmap from '../global/gmap.component' 

class RandomPlace extends Component { 
    render() { 
    return (
     <Gmap address={this.state.random.location} /> 

除其他事項外,其呈現的Gmap組件:

class Gmap extends Component { 
    componentDidMount() { 

    } 
    render() { 
    return (
     <div className="gmap-component"> 
     <p>{this.props.address}</p> 

<p>{this.props.address}</p>很好地顯示和更新當我點擊組件A上的「重新加載」按鈕時。此時,React Chrome擴展程序很好地顯示了道具的地址內容。並且看到它在「重新加載」操作中得到更新。

問題是,我不能似乎能夠在我的組件Gmap的內部功能到達道具屬性addresscomponentDidMount()aCustomFunction()。在類的頂部

componentDidMount() { 
    console.log('gmap did mount') 
    this.setState({address: this.props.address}) 
    let x = this.props.address 
    let y = this.state.address 

    console.log(x) 
    console.log(y) 

使用構造:

我已經測試了這個

constructor (props) { 
    super(props) 

    this.state = { 
     address: 'xx' 
    } 

但什麼也不顯示。我是React新手,肯定我缺少一些非常基本的東西,但無法找到它。 在此先感謝。

+0

你在日誌中看到什麼? – Andrew

+0

我得到了'undefined'和'xx'。 – kevin

+0

最好在你返回你的jsx之前檢查道具和狀態渲染,同時也應對chrome開發工具在調試這種情況時的幫助。 – Mateusz

回答

0

你問的是如何調用你的子組件的自定義函數嗎?如果是這樣,

<Gmap address={this.state.random.location} ref={(map) => { this.map = map; }} /> 

然後

this.map.aCustomFunction() 
+0

沒有,我想知道如何在孩子使用道具通過傳遞的位置(GMAP)元素的功能。雖然顯示器本身在渲染中工作。 – kevin

0

我不能完全肯定,但我認爲它會像:

  1. 在您的成分A,從國家address={this.state.random.location}集,你看。
  2. 隨機對象用componentDidMount()中的getRandomPlace()方法填充。
  3. 所以發生了什麼:首先你渲染的Gmap組件具有不確定的prop屬性,因爲組件A沒有調用componentDidMount()。
  4. 然後在組件A中觸發componentDidMount,你得到填充對象「random」,並且yuor組件Gmap recive normal prop addres,沒有未定義。這一新adderss道具和重新呈現組件,但是你在組件GMAP已經調用,並且不會引發更多componentDidMount()...

如果我是對的,你可以設置在A組份

constructor(){ 
    super(); 
    this.state={ 
     random: {location: "some test value"} 
    } 
} 

你會看到這個「一些測試值」,而不是你的控制檯日誌中定義。