Javascript 我的React组件状态是连续返回空对象
我试图为我的训练构建一个天气应用程序,但我遇到了一个问题 无论我做什么,我都有一个类型错误。我打算做的是从WeatherMapAPI获取json数据,然后 显示一些字符串,但我不能 以下是我的应用程序的主要内容Javascript 我的React组件状态是连续返回空对象,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我试图为我的训练构建一个天气应用程序,但我遇到了一个问题 无论我做什么,我都有一个类型错误。我打算做的是从WeatherMapAPI获取json数据,然后 显示一些字符串,但我不能 以下是我的应用程序的主要内容 import React, { Component } from 'react'; import { View, StyleSheet, Text } from 'react-native'; class Content extends Component{ constru
import React, { Component } from 'react';
import { View, StyleSheet, Text } from 'react-native';
class Content extends Component{
constructor(props) {
super(props);
this.state = {
data: this.props.weather.main,
};
}
render() {
return (
<View style={styles.content}>
<Text style={styles.city}>City Name</Text>
<Text style={styles.itemsize}>Weather {this.state.data}</Text>
<Text style={styles.itemsize}>Description</Text>
<Text style={styles.itemsize}>Temperature Celsius</Text>
<Text style={styles.itemsize}>Pressure</Text>
<Text style={styles.itemsize}>Humidity</Text>
</View>
);
}
}
const styles = StyleSheet.create({
content: {
flex: 1,
justifyContent: 'center',
alignItems:'center'
},
city: {
fontSize: 50,
padding: 20
},
itemsize: {
fontSize: 30,
padding: 5
}
})
export default Content;
在请求完成之前,您已经将
this.state.data
insideContent
设置为null
,并且当组件重新呈现时,它不会得到更新,因为构造函数在装载时只运行一次
从道具
设置状态
是一种反模式,只能在极少数情况下使用
相反,从this.props
读取天气数据,一旦父组件更新其状态,该数据将被更新
在访问.main
内部this.props.weather
之前,您还需要检查this.props.weather
是否为null
类内容扩展组件{
render(){
const{weather}=this.props
返回(
城市名称
Weather{Weather?Weather.main:null}
描述
摄氏温度
压力
湿度
)
}
}
主要问题是主组件中的此.state.data
是在创建内容组件后(调用其构造函数函数后)设置的
这将生成一个TypeError
,因为This.props.weather
是未定义的
,并且您正试图访问属性This.props.weather.main
解决此问题的最简单方法是直接使用props对象,而不是将这些props添加到状态,下面是一个示例:
<Text style={styles.itemsize}>Weather {this.props.weather}</Text>
Weather{this.props.Weather}
在父组件中,状态从不获取数据,并且始终保持为空。当我们想要从API获取数据时,我们应该使用一个名为react的生命周期方法。因此,在父组件中,您应该在componentDidMount中调用_getdata函数,或者在lifecycle方法中获取数据,如下面的代码,我认为这是一种更好的方法。另外,最初不要将状态设置为null。将其设置为空对象
import React,{Component}来自'React';
从“./Content”导入内容;
从“/GetWeather”导入GetWeather;
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
数据:{},
};
}
componentDidMount(){
GetWeather.GetWeather().then(json=>{
log(json);
this.setState({data:json});
});
}
render(){
console.log(this.state.data);
返回(
);
}
}
导出默认应用程序
function getLocation(lat, long) {
return `${API_STEM}lat=${lat}&lon=${long}&appid=${APP_ID}`;
}
function getWeather() {
return fetch(getLocation(LATTITUDE,LONGGITUDE))
.then(response => response.json())
.then(responseJson => {
return { main: responseJson.weather[0].main};})
.catch(err =>console.log(err));
}
export default {getWeather: getWeather};
<Text style={styles.itemsize}>Weather {this.props.weather}</Text>