简介
大家好,我是NextJS的新手.我正在使用外部API构建一个天气应用程序.我正在从API获取数据,并在前端展示它.
我想要什么?
我使用getServerSideProps()
获取数据.但我想要的是,用户/客户端在输入框中输入city
,然后单击,最后查看相应城市的天气详细信息.
我做了什么?
为此,我在组件中定义了city
个州,但现在我希望在getServerSideProps()
中访问该城市.
怎么做?
密码
import Head from "next/head";
import {useState} from 'react';
import Today_highlight from "./components/Today_highlight";
import Weather_Today from "./components/Weather_Today";
import Weather_week from "./components/Weather_week";
export default function Home({ results, results1 }) {
//console.log("res1 = ",results1);
const [city, setCity] = useState('Bhopal');
const handleChange = (e) => {
setCity(e.target.value);
//console.log(city)
}
const handleSubmit = (e) => {
e.preventDefault();
window.location.reload();
}
return (
<>
<Head>
<title>Weather-Lytics</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div className="min-h-full bg-red-400 flex flex-col lg:flex-row">
<label htmlFor="inputcity" className="w-15">Enter City</label>
<input
type="email"
className="form-control w-56 h-8"
id="inputcity"
value={city}
placeholder="Enter city"
onChange={handleChange}
/>
<button className="p-1 bg-slate-600 m-auto p-auto" onSubmit={handleSubmit}> Click</button>
<div className="bg-blue-300 w-full lg:w-1/4 lg:h-full">
<Weather_Today results={results} />
</div>
<div className="bg-green-500 w-full lg:h-full ">
<div className="min-h-full flex flex-col">
<div className="bg-yellow-400 w-full">
<Weather_week results1={results1} />
</div>
<div className="bg-orange-600 w-full">
<Today_highlight results={results} />
</div>
</div>
</div>
</div>
</>
);
}
export async function getServerSideProps({query}) {
//hereI want to access the city state
//query.term = city;
if(!query.term)
query.term = 'Bhopal'
//api-1
const url = `https://api.openweathermap.org/data/2.5/weather?q=${query.term}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
const res = await fetch(url);
const data = await res.json();
//console.log(data);
//api-2
const url1 = `http://api.openweathermap.org/data/2.5/forecast?q=${query.term}&appid=${process.env.NEXT_PUBLIC_API_KEY_1}`;
const res1 = await fetch(url1);
const data1 = await res1.json();
//console.log(data1);
return {
props: {
results: data,
results1: data1,
},
};
}