gpt4 book ai didi

javascript - 使用 componentDidUpdate 循环

转载 作者:行者123 更新时间:2023-12-03 05:37:38 27 4
gpt4 key购买 nike

我将一个自调用函数从 App 组件传递到 WeatherForecast 组件的 getBgColor 函数。这会从子组件 WeatherForecast 获取一个值,并将其传递到 App 组件以更新 this.state.appColorClass

*getBgColor 函数位于 componentDidUpdate() 内部,它会创建一个循环并使浏览器崩溃。新的 react ,不知道如何解决这个问题。

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>&deg;</sup></h1>
<h1>{this.displayCity(this.props.weather)}</h1>
</div>
);
}
}

最佳答案

循环是递归的,因为在 WeatherForecast 组件安装(更新)后,它会调用 getBgColor 属性,该属性设置父状态,触发子更新,子更新调用 getBgColor...然后你就得到了图片。

老实说,我可能会建议稍微移动一下逻辑......因为 weather 作为 Prop 传入,然后颜色被传回,看起来更像是“React”在父组件中处理它。当数据流向下游时更容易遵循。假设您的要求导致您达到这个位置,在 setAppColor 中添加一个简单的检查就可以解决该问题。

setAppColor(colorClass) {
alert("set className");
// only set state if it's changing
if (colorClass != this.state.appColorClass) {
this.setState({ appColorClass: colorClass });
}
}

关于javascript - 使用 componentDidUpdate 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40666463/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com