经过一系列代码试用后,我无法将 API 中的 JSON 文件存储到状态中
在完全实现之前,我一直在尝试在浏览器控制台控制台上显示 JSON 响应。我有这个代码:
//const API;
class WeatherApp extends React.Component{
constructor(props){
super(props);
this.state = {
location: "",
reports:[]
}
}
//functions should be written outside the constructor method
onSubmit = event => {
//prevents default loading of the page when this function "onSubmit"
//is called
event.preventDefault();
//saving the value of the textbox to a variable/const
if(this.searchbox.value !== ""){
const searchResult = this.searchbox.value;
//update the state object
this.setState({
location: searchResult + " weather report"
});
}else{
alert("please ensure that field is not empty!");
return;
}
};
//${this.searchbox.value + KEY}
componentDidMount(){
if(this.searchbox.value !== ""){
fetch(`api.openweathermap.org/data/2.5/forecast?q=${this.searchBox.value + KEY} `, {
method: "GET",
dataType: "JSON"
})
.then( data =>
this.setState({ reports: [...this.state.reports, data.list ], })
);
}
}
render(){
console.log(this.state.reports);
return(
<div className="weather-app">
<WeatherAppHeader />
<div className="weather-body">
<div className="entry-pane">
<form onSubmit ={this.onSubmit} >
<input
type="text"
id="search-box"
placeholder="Location e.g Abuja, NG"
size="40"
ref={input => this.searchbox = input} />
<button type="submit" id="search-btn">search</button>
</form>
</div>
<SearchedLocation location={this.state.location} />
<WeatherReport reports={this.state.reports} />
</div>
</div>
);
}
}
但我没有返回包含 JSON 对象的响应,而是得到了这个响应。请问我该如何解决这个问题?
[ length: 0 __proto__: Array(0)]