[英]React how to access props from constructor and then make a component based on the props/state
我不太确定如何正确地问这个问题,但是我将在这里解释我想做的事情:
所以我有这个父组件,它可以像这样创建一个组件:
<CurrentTemperature cityName={this.state.cityName}></CurrentTemperature>
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获取当前温度,然后在Component中显示这两个温度。 但是,如果我尝试从非城市温度div以外的任何地方进行console.log(this.props.cityName),则我总是会得到一个空字符串。 这里发生了什么?
cityName是父组件的状态。 我猜父组件将异步获取“ cityName”。 对? 在这种情况下,您必须将温度放入父组件作为其状态。 并且您必须在父组件中插入API调用。 CurrentTemperature组件的行为类似于纯函数组件。
const CurrentTemperature = ({temperature, cityName}) => { return ( <div className="city-temperature"> {cityName} {temperature} </div> ); }
我想这不仅是解决方案,而且是最好的DX。
在API调用完成之前,将调用构造函数并设置cityName
内部状态。
我建议您直接使用道具,而不是在状态内部存储值。
<div className="city-temperature">
{this.props.cityName} {this.state.temperature}
</div>
API调用完成后,组件将重新呈现并显示数据。
注意 :如果您确实要在状态内部存储它,请考虑使用getDerivedStateFromProps
生命周期挂钩。
您可以删除this
在你的构造,然后用this.state.cityName
constructor(props) {
super(props);
this.state = {
temperature: 0,
cityName: props.cityName,
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.