我正在將App
組件的自調用函數傳遞給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>
);
}
}
將thisComponentUpdate添加到WeatherForecast,並在this.props.weather === nextProps.weather時返回false。或者取決於你想要做什麼,將getBgColor的調用移動到componentDidMount,以便它只被調用一次。 –
' this.setAppColor(color)} />''可以只是' ',不需要附加功能 –