在这个天气应用程序中,我希望用户在"Body"组件中键入一个城市,并通过更新"results"组件来显示城市的天气结果.
当我将搜索查询从"Body"导出为prop cityProp={this.state.city}
时,我很难将其存储为{this.state.city}
存储到API调用中.
我能够访问并将输入的城市名称记录到控制台.但是,提交它似乎对显示的位置没有影响.
目标是显示输入城市的温度.
应用程序:
import "./App.css";
import Header from "./Header";
import Body from "./Body";
function App() {
return (
<div>
<Header />
<Body />
</div>
);
}
export default App;
正文:
import React, { Component } from "react";
import "./App.css";
import Results from "./Results";
import { useState } from "react";
class Body extends Component {
constructor(props) {
super(props);
this.state = { city: "London" };
}
handleCityChange = (e) => {
this.setState({ city: e.target.value });
};
handleSubmit = (e) => {
e.preventDefault();
// this.setState({ city: e.target.value });
};
render() {
return (
<div >
<form className="SearchForm" onSubmit={this.handleSubmit}>
<label>
<input
value={this.state.city}
onChange={this.handleCityChange}
></input>
<button>Go</button>
</label>
</form>
<Results cityProp={this.state.city} />
</div>
);
}
}
export default Body;
结果:
import "./App.css";
import React from "react";
import { useState, useEffect } from "react";
const Results = (props) => {
const [forecast, setForecast] = useState([]);
const [location, setLocation] = useState([]);
useEffect(() => {
const getWeather = async () => {
try {
fetch(
`http://api.weatherapi.com/v1/forecast.json?key=47b6acea5d204134b4661938220707&q="${props.cityProp}"&days=3&aqi=no`
).then((response) => {
response.json().then((data) => {
setForecast(data.forecast);
setLocation(data.location);
});
});
} catch (err) {
console.log("Error");
}
};
getWeather();
}, []);
const renderedContent = forecast.forecastday
? forecast.forecastday.map((item) => {
return (
<div key={item.date_epoch}>
<div>{item.day.maxtemp_c}</div>
</div>
);
})
: null;
return (
<div>{renderedContent}</div>
);
};
export default Results;