2017-05-01 16 views
4

私は機能コンポーネントGetWeatherを持っています。GetLocation関数の結果を、GetWetaherが別のget要求(下の例ではその小道具のみをレンダリングする)を行うための基礎となる小道具として渡したいとします。私はそれがComponentDidMount内部で起こることがあると思いますが、わからないそれを行う方法をReactで小道具として機能を渡すには?

function GetLocation() { 
     axios.get('http://ipinfo.io') 
      .then((res) => {  
      return res.data.loc; 
      }) 

     } 
    function GetWeather(props) { 
    //more code here, including another get request, based on props 
     return <h1>Location: {props.location}</h1>;  
    } 

    class LocalWeather extends Component {   
     componentDidMount() {  
     //???  
     }   
     render() { 
     return (
      <div >       
       <GetWeather location={GetLocation}/> //???            
      </div> 
     ); 
     } 
    } 

更新:ので、下記の私のため

function GetWeather(props) { 
    return <h3>Location: {props.location}</h3>; 
} 

class LocalWeather extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     location: [] 
    }; 
    } 
    getLocation() { 
    axios.get('http://ipinfo.io') 
     .then((res) => {  
     this.setState({location:res.data.loc});   
     })   
    } 

    componentDidMount() {  
    this.getLocation();  

    } 
    render() { 
    return (
     <div >      
      <GetWeather location={this.state.location}/>             
     </div> 
    ); 
    } 
} 
+1

あなたはあなたの質問にもっと凝っていることができますか?少し曖昧です。しかし、これまでの私の理解では、 'LocalWeather'コンポーネントコンストラクタでデフォルト状態を作成し、' componentDidMount'の中で 'get Local 'を呼び出し、' LocalWeather'コンポーネントに戻り値を設定することができます。 'LocalWeather'コンポーネントの状態を介して' GetWeather'コンポーネントへの位置をpropsとして返します。 –

+0

あなたは私の質問が正しいと思う...それは今私のために働く;) – irom

答えて

4

を働いているダミアンからの提案に基づいて、あなたはまた、代わりにそれを行うことができます

constructor() 
    { 

     super(); 

     this.state= 
     { 
     Location:[] 


     } 

    } 
    function GetLocation() { 
     axios.get('http://ipinfo.io') 
      .then((res) => { 
this.setState ({  
      Location:res.data.loc; 
}) 
      }) 

     } 
    function GetWeather(props) { 

     return <h1>Location: {this.props.location}</h1>;  
    } 

    class LocalWeather extends Component {   
     componentDidMount() {  
     //???  
     }   
     render() { 
     return (
      <div >       
       <GetWeather location={this.GetLocation.bind(this)}/>            
      </div> 
     ); 
     } 
    } 
関連する問題