我有一个函数式组件GetWeather,我想将GetLocation函数的结果作为属性传递给它,根据这个属性,GetWetaher将执行另一个get请求(在下面的示例中,它只呈现其属性)。我认为这必须发生在ComponentDidMount内部,但不确定如何做到这一点。
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>
);
}
}
更新: 根据下面 Damian 的建议,以下方法对我有效
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
中调用获取位置的方法,并将返回值设置为LocalWeather
组件。之后,您可以通过LocalWeather
组件的状态将位置作为props传递给GetWeather
组件。 - theterminalguy