[英]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.