[英]How to access a state variable in getServerSideProps() in NextJS?
大家好,我是 NextJS 的新手。 我正在使用外部 API 构建天气应用程序。 我正在从 API 获取数据并将其呈现在前端。
我正在使用getServerSideProps()
获取数据。 但我想要的是用户/客户端在输入框中输入city
,然后点击,最后看到各自城市的天气详情。
为此,我在组件中定义了一个city
state,但现在我希望在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,
},
};
}
handleSubmit
中的代码是否是获取数据的正确方法? State 客户端的变量无法从getServerSideProps
访问,因为它在服务器上运行。 您必须通过查询参数传递数据以使其在服务器端可用。
要将city
作为查询参数传递给getServerSideProps
,您可以在handleSubmit
function 中使用router.push
。
const handleSubmit = (e) => {
e.preventDefault();
router.push(`/?term=${city}`);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.