【问题标题】:How to pass the data input from one component into another component?如何将数据输入从一个组件传递到另一个组件?
【发布时间】:2022-08-14 22:49:04
【问题描述】:

介绍问题

我是初学者ReactJS 学习者使用 OpenWeather API 开发一个简单的天气应用程序。该应用程序旨在从两个组件中获取数据:一个返回用户输入的当前天气,另一个返回未来 5 天的天气预报。

在输入字段中输入城市名称时,控制台上会显示以下消息:

GET https://api.openweathermap.org/data/2.5/weather?q=undefined&units=metric&appid=${Api.key} 400(错误请求)

我不知道如何将数据从搜索组件传递到应用程序组件。说真的,我尝试了很多替代方案,但都没有成功。有注释的代码行显示我到目前为止的最后一次尝试。

(忽略 ForecastWeather,因为该组件为空)

我知道你们都是很忙的人,但我会以尊重的方式感谢您的帮助。甚至对我必须学习的内容(例如callBack)的建议也是受欢迎的。我已经尝试过这个:

https://stackoverflow.com/questions/56943427/whether-to-save-form-input-to-state-in-onchange-or-onsubmit-in-react

https://sebhastian.com/react-onchange/

代码转发如下:

应用程序.js

import React, { useState } from \"react\";
import { Api } from \"./Api\";
import {
  Search,
  CurrentWeather,
  ForecastWeather,
  Footer,
} from \"./components/index\";
import \"./App.css\";

function App() {
  const [getCity, setGetCity] = useState();
  const [weatherData, setWeatherData] = useState(null);
  const [forecastData, setForecastData] = useState(null);

  const handleSearchLocation = (dataSearch) => {
    const weatherDataFetch = fetch(
      `${Api.url}/weather?q=${getCity}&units=metric&appid=${Api.key}`
    );
    const forecastDataFetch = fetch(
      `${Api.url}/forecast?q=${getCity}&units=metric&appid=${Api.key}`
    );

    Promise.all([weatherDataFetch, forecastDataFetch])
      .then(async (response) => {
        const weatherResponse = await response[0].json();
        const forecastResponse = await response[1].json();

        setGetCity(dataSearch);
        setWeatherData(weatherResponse);
        setForecastData(forecastResponse);
      })
      .catch(console.log);
  };

  return (
    <div className=\"App\">
      <Search
        searchResultData={handleSearchLocation}
        textPlaceholder=\"Search for a place...\"
      />
      {weatherData && <CurrentWeather resultData={weatherData} />}
      <ForecastWeather resultData={forecastData} />
      <Footer />
    </div>
  );
}

export default App;

搜索.jsx

import React, { useState } from \"react\";

function Search({ textPlaceholder, searchResultData }) {
  const [searchCity, setSearchCity] = useState(\"\");

  //const handlerOnChange = ( event, dataSearch ) => {
  //setSearchCity(event.target.value);
  //setSearchCity(dataSearch);
  //searchResultData(dataSearch);
  //};

  return (
    <div className=\"componentsBoxLayout\">
      <input
        value={searchCity}
        //onChange={handlerOnChange}
        onChange={(event) => setSearchCity(event.target.value)}
        onKeyDown={(event) => event.key === \"Enter\" && searchResultData(event)}
        placeholder={textPlaceholder}
      />
    </div>
  );
}

export default Search;

当前天气.jsx

import React from \"react\";

function CurrentWeather({ resultData }) {
  return (
    <div className=\"componentsBoxLayout\">
      <p>{resultData.name}</p>
    </div>
  );
}

export default CurrentWeather;

ForecastWeather.jsx(空)

import React from \'react\';

function ForecastWeather() {
  return (
    <div className=\"componentsBoxLayout\">ForecastWeather</div>
  )
}

export default ForecastWeather;

api.js

const Api = {
  url: \"https://api.openweathermap.org/data/2.5\",
  key: \"etcetc\",
  img: \"https://openweathermap.org/img/wn\",
};

export { Api };

Yippee-ki-yay

  • 在使用weatherDataFetch 之后,您使用setGetCity。您希望如何定义它?
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。
  • @KonradLinkowski 感谢您抽出宝贵时间,但即使您提供帮助,我也无法理解如何在 weatherDataFetch 之前使用 setGetCity。我尝试在 const weatherDataFetch = fetch( 之前放置或作为参数或空字符串传递,但同样的问题仍然存在。一切顺利。
  • 我不明白你想如何在不知道城市的情况下询问城市的天气数据。你有一个Search 组件,但你从不使用这个组件的数据

标签: javascript reactjs api openweathermap


【解决方案1】:

您不能在此函数中使用 getCity:

const handleSearchLocation = (dataSearch) => {
    const weatherDataFetch = fetch(
      `${Api.url}/weather?q=${getCity}&units=metric&appid=${Api.key}`
    );
    const forecastDataFetch = fetch(
      `${Api.url}/forecast?q=${getCity}&units=metric&appid=${Api.key}`
    );

    Promise.all([weatherDataFetch, forecastDataFetch])
      .then(async (response) => {
        const weatherResponse = await response[0].json();
        const forecastResponse = await response[1].json();

        setGetCity(dataSearch);
        setWeatherData(weatherResponse);
        setForecastData(forecastResponse);
      })
      .catch(console.log);
  };

getCity 是在该函数上定义的,因此当您尝试使用它时它不存在,除非您稍后需要 getCity 用于另一个组件,否则我将删除它,因为它是多余的并执行以下操作:

const handleSearchLocation = (dataSearch) => {
    const weatherDataFetch = fetch(
      `${Api.url}/weather?q=${dataSearch}&units=metric&appid=${Api.key}`
    );
    const forecastDataFetch = fetch(
      `${Api.url}/forecast?q=${dataSearch}&units=metric&appid=${Api.key}`
    );

    Promise.all([weatherDataFetch, forecastDataFetch])
      .then(async (response) => {
        const weatherResponse = await response[0].json();
        const forecastResponse = await response[1].json();

        setWeatherData(weatherResponse);
        setForecastData(forecastResponse);
      })
      .catch(console.log);
  };

当您在搜索组件上运行 searchResultData 时,您会发送您正在寻找的城市。请记住,useState 将触发重新渲染,但如果状态发生变化,之前已经运行的函数将永远不会获得状态的新值

【讨论】:

  • 非常感谢你所做的一切。此更改有效,但出现了另一个问题:404 错误。然后,我从 Search 组件更新以下行:onKeyDown={(event) =&gt; event.key === "Enter" &amp;&amp; searchResultData(searchCity)} 我已将 searchResultData 道具从 event 更改为 searchCity。
  • API上的404是什么?
  • 我相信不在 API 本身。这是错误:GET https://api.openweathermap.org/data/2.5/weather?q=[object%20Object]&amp;units=metric&amp;appid=fc8975bd4701139dcd78e2e288cc3807 404 (Not Found) 但现在没关系。
  • 您需要确保正确发送输入的值,我可以看到您没有将值正确存储在状态中
  • 我将粘贴当前搜索代码和当前天气:import React, { useState } from "react"; function Search({ textPlaceholder, searchResultData }) { const [searchCity, setSearchCity] = useState(""); return ( &lt;div className="componentsBoxLayout"&gt; &lt;input value={searchCity} onChange={(event) =&gt; setSearchCity(event.target.value)} onKeyDown={(event) =&gt; event.key === "Enter" &amp;&amp; searchResultData(searchCity)} placeholder={textPlaceholder} /&gt; &lt;/div&gt; ); } export default Search;
猜你喜欢
  • 2019-11-06
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 2018-05-02
  • 2019-09-02
相关资源
最近更新 更多