简介

大家好,我是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,
    },
  };
}

Also I am in doubt whether the code inside handleSubmit is correct way to fetch data ?

推荐答案

在服务器上运行时,无法从getServerSideProps访问客户端的状态变量.必须通过查询参数传递数据,才能使其在服务器端可用.

要将city作为查询参数传递给getServerSideProps,可以在handleSubmit函数中使用router.push.

const handleSubmit = (e) => {
    e.preventDefault();
    router.push(`/?term=${city}`);
}

Javascript相关问答推荐

当我使用jQuery时,我的图标显示为[对象对象]

获取POS餐厅会话用户/收银员

Promise.all立即跳到那时,而不是调用所有Promise

设置默认值后动态更新japbox或调色板

Angular:ng-contract未显示

对象和数字减法会抵消浏览器js中的数字

我无法在NightWatch.js测试中获取完整的Chrome浏览器控制台日志(log)

将json数组项转换为js中的扁平

Vue:ref不会创建react 性属性

Snowflake JavaScript存储过程返回成功,尽管预期失败

我在我的Java代码中遇到了问题,代码的一部分看不到先前定义的对象

如何在bslib nav_insert之后更改导航标签的CSS类和样式?

环境值在.js文件/Next.js中不起作用

<;img>;标记无法呈现图像

为什么云存储中的文件不能公开使用?

使用父标签中的Find函数查找元素

Jexl to LowerCase()和Replace()

FireBase FiRestore安全规则-嵌套对象的MapDiff

React Refs不与高阶组件(HOC)中的动态生成组件一起工作

无法使用npm install安装react-dom、react和next