【发布时间】:2018-03-02 09:59:01
【问题描述】:
编辑:所以我在堆栈溢出方面遇到了一些麻烦,不得不重新输入一些东西....包括 Weather weatherData={this.state.weatherData} 我不小心在这里输入错误天气weatherData={weatherData}。但我也确实在我的代码上犯了一个输入错误,那就是 setState。我是 reactjs 的新手,有些语法我觉得很奇怪,所以这可能就是我有语法错误的原因。所以我最终修复了一些东西,但仍然出现错误“this.setState 不是函数”。我想这可能是一个范围问题,所以我创建了一个新方法 updateWeatherData,瞧,它奏效了。
所以我正在尝试制作一个天气应用程序。一旦this.state.weatherData中有数据,我想要做的是加载名为Weather的子组件。我已经检查了一个 console.log 并且数据是从 ajax 调用返回的,但我似乎无法设置它。我收到的错误消息是“无法读取未定义的属性 'weatherData'”
var React = require('react');
var Weather = require('./Weather');
class App extends React.Component{
constructor(props)
{
super(props);
this.state = {
weatherData: null,
};
this.getDataFromLatLng = this.getDataFromLatLng.bind(this);
this.showPosition = this.showPosition.bind(this);
}
updateWeatherData (results)
{
this.setState({
weatherData:results
});
}
componentDidMount()
{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
showPosition(position)
{
this.getDataFromLatLng(position.coords.latitude, position.coords.longitude);
}
getDataFromLatLng(lat, lng)
{
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+lng+"&units=metric&appid=ID",
type:"GET",
dataType:"jsonp",
//CHANGED FROM THIS:
/*success:function(results){
//RESULTS COME BACK
console.log(results);
this.setState=({
weatherData:results
});
console.log(this.state.weatherData);
//But no weatherData is being set
},*/
//TO THIS:
success:this.updateWeatherData,
error: function(xhr, status, error) {
console.log(xhr.responseText + " " + status, " " + error);
}
});
}
render()
{
return(
<div id="container">
Hello From App
{this.state.weatherData != null
? <Weather weatherData={this.state.weatherData}/>
: <p>Loading...</p>
}
</div>
);
}
}
module.exports = App;
【问题讨论】:
-
请显示console.log(results);应该是
<Weather weatherData={this.state.weatherData}/> -
您将无法看到更改后的状态。这就是
console.log(this.state.weatherData)中没有价值的原因。将weatherData={weatherData}更改为weatherData={this.state.weatherData}。
标签: javascript reactjs