这是保存所有内容的主要文件。
import Titles from "./components/Titles"
import Form from "./components/Form"
import Weather from "./components/Weather"
const API_KEY = "f879356f52a3f6dcf8295811ee1eb492";
//creats instance of APP and extends to react.Component
class App extends React.Component{
state = {
temperature: undefined,
city: undefined,
country: undefined,
humidity: undefined,
description: undefined,
error: undefined
}
// Need async for api call
getWeather = async (e) => { // arrow function
e.preventDefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
// targets values in form//
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric`);
//makes api call....Need tou use AWAT followed by FETCH
const data = await api_call.json();
//converting API call to JSON format then assanising to data
console.log(data);
// Sets data that will be passed to state//
this.setState =({
temperature: data.main.temp,
city: data.name,
country: data.sys.country,
humidity: data.main.humidity,
description: data.weather[0].description,
error: ""
});
}
render(){
return(
<div>
<Titles />
<Form getWeather={this.getWeather} />
<Weather
temperature={this.state.temperature}
city={this.state.city}
country={this.state.country}
humidity={this.state.humidity}
description={this.state.description}
error={this.state.error}
/>
</div>
);
}
}
export default App;
这是天气成分
import React from "react";
class Weather extends React.Component{
render(){
return(
<div>
<p>location{this.props.city}, {this.props.country}</p>
<p>Temprature {this.props.temperature}</p>
<p>humidity: {this.props.humidity}</p>
<p>Conditions{this.props.description}</p>
</div>
);
}
}
export default Weather;
这是表单组件,当您按下提交按钮时,它应该填充道具。它可以在日志中显示,但不会在屏幕上显示。
import React from "react";
class Form extends React.Component{
render(){
return(
<form onSubmit={this.props.getWeather}>
<input type="text" name="city" placeholder="city...." />
<input type="text" name="country" placeholder="Country..." />
<button> Get Weather</button>
</form>
);
}
}
export default Form;
这是你们要查看的最后一个组件 import&#34; react&#34;;
class Titles extends React.Component {
render(){
return(
<div>
<h1>Weather App</h1>
<p> Find Temp, conditions and more</p>
</div>
);
}
}
export default Titles;
答案 0 :(得分:3)
this.setState =({
是一项任务,而非方法调用。
你想要
this.setState({