2017-04-09 121 views
1

我使用的是React Native 0.43。我有兩個組件,分別命名爲ParentComponentChildComponent。我想傳遞一些從父母到孩子的道具。我在父組件使用下面的代碼(刪節版):React Native:傳遞組件和componentWillMount()方法之間的道具

export default class ParentComponent extends Component { 

    constructor(props) { 
    super(props); 

    this.state = { 
     latitude: 34.7821, 
    }; 
    } 

    render() { 
    return (
     <View> 
     <ChildComponent latitude={this.state.latitude} /> 
     </View> 
    ); 
    } 

} 

我的孩子組件如下:

export default class ChildComponent extends Component { 

    constructor(props) { 
    super(props); 

    this.state = { 
     latitude: props.latitude, 
    }; 
    } 

    componentWillMount() { 
    console.log('Before Mount: ' + this.state.latitude) 
    } 

    render() { 
    return (
     <Text>{'Mounted: ' + console.log(this.state.latitude)}</Text> 
    ); 
    } 
} 

現在,我的控制檯顯示以下結果:

2:14:12 AM: Before Mount: null 

2:14:12 AM: Mounted: null 

2:14:12 AM: Mounted: 34.7821 

現在我的原始代碼中的componentWillMount()有一個API調用Web服務,這取決於this.state.latitude的值,顯然沒有通過,至少在第一次呈現。在第二次渲染時,當this.state.latitude值變爲可用時,僅執行render()函數,但在componentWillMount()函數中需要此值。

我在做什麼錯在這裏?

+1

你可以在ComponentDidMount –

回答

5

我沒能在componentWillMount獲得道具的價值,因爲這種方法只執行一次,只是初始渲染之前。由於道具沒有在第一次渲染時從父組件傳遞到子組件,我通過在子組件中使用componentWillReceiveProps方法來解決問題。它接收後續渲染的道具並更新我的子組件中的原始狀態。這使我能夠訪問我的狀態值。我用來解決的代碼如下:

componentWillReceiveProps(nextProps) { 
     // update original states 
     this.setState({ 
     latitude: nextProps.latitude, 
     }); 
    } 
3

你必須用「this」這個詞來稱呼你的道具。

+0

中處理它不,不是。狀態值用我的給定代碼在第二次渲染迭代上打印。 –

相關問題