コンポーネントからgetBgColor
ファンクションへの自己呼び出し関数を渡します。WeatherForecast
コンポーネントです。これは、子コンポーネントWeatherForecast
から値を取得し、App
のコンポーネントに渡して、this.state.appColorClass
を更新します。loop with componentDidUpdate
* getBgColor
機能がありませんcomponentDidUpdate()
ループを作成してブラウザをクラッシュします。この問題を解決する方法がわからない場合は、新しく反応してください。
export default class App extends Component {
constructor(props) {
super(props);
this.state = { appColorClass: 'app-bg1' };
}
setAppColor(colorClass) {
alert("set className");
this.setState({ appColorClass: colorClass });
}
render() {
return (
<div className={"app-container " + this.state.appColorClass}>
<div className="main-wrapper">
<WeatherForecast getBgColor={color => this.setAppColor(color)} />
</div>
</div>
);
}
}
class WeatherForecast extends Component {
componentDidUpdate() {
console.log('Component DID UPDATE!')
//The function `setAppColor` from `App` component is passed into `getBgColor`
this.props.getBgColor(this.appColor(this.props.weather));
}
appColor(weatherData) {
console.log("app color working");
let temp = 0;
if (typeof weatherData === 'undefined' || weatherData === null) {
console.log(" initial Color went through");
return 'app-bg1';
}
temp = Math.round(weatherData.list[0].main.temp - 273.15);
if (temp <= -30) {
return "app-bg1";
}
if (temp >= -29 && temp <= -21) {
return "app-bg2";
}
if (temp >= -20 && temp <= -11) {
return "app-bg3";
}
if (temp >= -10 && temp <= 4) {
return "app-bg4";
}
if (temp >= 5 && temp <= 15) {
return "app-bg5";
}
if (temp >= 16 && temp <= 24) {
return "app-bg6";
}
if (temp >= 25 && temp <= 32) {
return "app-bg7";
}
if (temp >= 33 && temp <= 38) {
return "app-bg8";
}
if (temp >= 39) {
return "app-bg9";
}
}
render() {
return (
<div className="text-center col-xs-12">
<h1 id="temp">{this.displayTemp(this.props.weather)}<sup>°</sup></h1>
<h1>{this.displayCity(this.props.weather)}</h1>
</div>
);
}
}
weatherForecastにshouldComponentUpdateを追加し、this.props.weather === nextProps.weatherがfalseの場合はfalseを返します。または、何をしようとしているかに応じて、getBgColorの呼び出しをcomponentDidMountに移動して、一度だけ呼び出されるようにします。 –
' this.setAppColor(color)} />'はちょうど ' 'であり、追加機能は不要です。 –