javascript - 如何使用 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>
);
}
我想计算当温度和湿度传递到组件时的热指数并显示在湿度部分。
解决方案
如果要在传入组件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>
);
}
推荐阅读
- python-3.x - 如何仅提取数字并打印为字符串
- javascript - 浏览器如何将 CSS 百分比单位转换为像素?
- node.js - 如何在主进程中使用 electron.js 中的真正加密模块?
- java - Tictac toe 游戏不断停止并出现 logcat 错误 java.lang.IllegalStateException:Could not execute method for android:onClick
- javascript - 在javascript中录制麦克风也可以捕捉扬声器声音
- qr-code - 在理解 QR 码版本以选择/执行 Reed Solomon 码时遇到问题
- python - 解析所需文件的列表python
- flutter - 输入'列表
' 不是类型 'List 的子类型 ' 在类型转换中 - autodesk-forge - 查看器扩展网络呼叫超时
- oauth - 使用哪个 O Auth 流程来验证在前端获得的第 3 方访问令牌