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>
);
}
}
あなたはあなたの質問にもっと凝っていることができますか?少し曖昧です。しかし、これまでの私の理解では、 'LocalWeather'コンポーネントコンストラクタでデフォルト状態を作成し、' componentDidMount'の中で 'get Local 'を呼び出し、' LocalWeather'コンポーネントに戻り値を設定することができます。 'LocalWeather'コンポーネントの状態を介して' GetWeather'コンポーネントへの位置をpropsとして返します。 –
あなたは私の質問が正しいと思う...それは今私のために働く;) – irom