首页 > 解决方案 > 如何使用 2 个道具进行数学运算?

问题描述

示例:我想乘以从 API 获取的 2 个道具(Temp* Humidity),并希望在新值出现时更新结果(用户输入新城市,然后温度和湿度发生变化)

这是我的 fetching.js

fetchData = q => {
fetch(
  `http://api.openweathermap.org/data/2.5/weather?q=${q},th&units=metric&APPID=${API_KEY}`
)
  .then(response => response.json())
  .then(json => {
    this.setState({
      currentWeather: {
        temp: json.main.temp,
        icon: json.weather[0].icon,
        description: json.weather[0].description,
        humidity: json.main.humidity,
        datetime: json.dt
      }
    });
  })
  .catch(error => {
    console.warn(error);
  });
};

这是我的前端

  render() {
    return (
      <View style={styles.viewStyle}>
        <View style={styles.dataStyle}>
          <Text style={styles.textStyle}>Temperature </Text>
          <Text style={styles.textStyle}>{this.props.temp} °C</Text>
        </View>
        <View style={styles.dataStyle}>

      <Image
            style={{ width: 100, height: 100 }}
            source={{
          uri: `http://openweathermap.org/img/w/${this.props.icon}.png`
        }}
      />
      <Text style={styles.textStyle}>{this.props.description}</Text>
    </View>
    <View style={styles.dataStyle}>
      <Text style={styles.textStyle}>Humidity</Text>
      <Text style={styles.textStyle}>{this.props.humidity} %</Text>
    </View>
  </View>
);
}

我想计算当温度和湿度传递到组件时的热指数并显示在湿度部分。

标签: javascriptreactjsreact-native

解决方案


如果要在传入组件props时进行乘法运算,请使用componentWillReceiveProps方法。props

每当组件收到新的 props 时,都会执行componentWillReceiveProps方法。

componentWillReceiveProps(Props) {
          let heat_index = props.Temp* props.Humidity;
          this.setState({heat_index : heat_index});
        }

    render() {
        return (
       <View>
      <Text> The Heat Index is {this.state.heat_index} </Text>
      </View>
    );
}

推荐阅读