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

* 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>&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 });
  }
}

10-07 14:08