2017-04-09 16 views
1

私はReact Native 0.43を使用しています。私はParentComponentChildComponentという2つのコンポーネントを持っています。私は、親コンポーネントから子コンポーネントにいくつかの小道具を渡したいと思います。私の子コンポーネントは以下の通りである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()私の元のコードでは、明らかに最初のレンダリングで、渡されていないthis.state.latitudeの値に依存するWebサービスへのAPI呼び出しがあります。 2番目のレンダリングで、this.state.latitudeの値が利用可能になると、render()関数だけが実行されますが、私はcomponentWillMount()関数でこの値を必要とします。

私はここで間違っていますか?

+1

あなたはComponentDidMount –

答えて

5

私はこの方法が唯一のちょうど最初のレンダリングの前に、一度だけ実行されるので、componentWillMountで小道具値を受信することができませんでした。最初のレンダリングでは、小道具が親コンポーネントから子コンポーネントに渡されていないので、子コンポーネントでcomponentWillReceivePropsメソッドを使用して問題を解決します。それは後続のレンダリングで小道具を受け取り、子コンポーネントの元の状態を更新します。私の状態価値にアクセスすることができます。私は解決するために使用するコードは以下の通りです:

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

「この」という言葉をあなたの小道具と呼ぶ必要があります。

+0

でそれを扱うことができるいいえ、それはできません。状態値は、指定されたコードで2番目のレンダリング反復で印刷されます。 –

関連する問題