我不太确定如何正确提出这个问题,但我会在这里解释我想做什么:
所以我有这个父组件,它创建一个组件,如下所示:
<CurrentTemperature cityName={this.state.cityName}></CurrentTemperature>
当前温度组件如下所示:
import React, { Component } from "react";
import "../App.css";
export default class CurrentTemperature extends Component {
constructor(props) {
super(props);
this.state = {
temperature: 0,
cityName: this.props.cityName,
};
}
componentDidMount() {
//fetch the temperature from api here
}
render() {
return (
<div>
<div className="city-temperature">
{this.state.cityName} {this.state.temperature}
</div>
</div>
);
}
}
我要做的就是从父级读取城市名称,然后从我的 API 获取当前温度,然后在组件中显示这两个温度。但是,如果我尝试从城市温度div内部以外的任何地方控制台.log(this.props.cityName(,我总是得到一个空字符串。这是怎么回事?
cityName 是父组件的状态。我想父组件会异步获取"cityName"。右?如果是这种情况,则必须将父组件中的温度作为其状态。并且您必须在父组件中插入 API 调用。当前温度组件的行为类似于纯函数组件。
const CurrentTemperature = ({temperature, cityName}) => {
return (
<div className="city-temperature">
{cityName} {temperature}
</div>
);
}
我想这不仅是解决方案,也是最好的DX。
可以在构造函数中删除this
,然后使用this.state.cityName
constructor(props) {
super(props);
this.state = {
temperature: 0,
cityName: props.cityName,
};
}