示例:我想乘以从API提取的2个道具(Temp * 湿度)并想在新值到来时更新结果(用户输入新城市,然后更改温度和湿度)
这是我的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>
);
}
我想计算将温度和湿度传递给组件并显示在湿度部分时的热指数。
答案 0 :(得分:0)
您应该在componentDidMount()生命周期事件中调用提取。如果状态中的任何数据发生更改,则将重新呈现组件。
componentDidMount仅在客户端第一次渲染后执行。这是应该进行AJAX请求和DOM或状态更新的地方。此方法还用于与其他JavaScript框架以及延迟执行的任何函数(例如setTimeout或setInterval)集成。我们正在使用它来更新状态,以便我们可以触发其他生命周期方法。
http://www.tutorialspoint.com/reactjs/reactjs_component_life_cycle.htm
答案 1 :(得分:0)
如果要在props
传递到component时乘以props
,请使用 componentWillReceiveProps 方法。
每当组件收到新道具时,就会执行 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>
);
}