【问题标题】:Getting User Input in React Js in Fetch statement在 Fetch 语句中获取 React Js 中的用户输入
【发布时间】:2021-07-03 05:52:09
【问题描述】:

我创建了一个从 api 获取天气数据的代码。在链接中,我给出了一个地方 q=chennai。我需要更改此地点字段取决于用户。那就是我想从用户那里得到这个位置。我如何使用 react 来做到这一点

import React,{useState,useEffect} from 'react';

const Home1=()=>{
    const[info,setInfo]=useState({
        name:"loading !!",
        temp:"loading",
        humidity:"loading",
        desc:"loading",
    })
    useEffect(()=>
    {
        getWeather()
    })
    const getWeather=()=>
    {
        fetch('http://api.openweathermap.org/data/2.5/weather?q=chennai&appid=bd2d67a73f2dc8279......')
        .then(data=>data.json())
        .then(results=>{
           //console.log(results)
           setInfo({
               name:results.name,
               temp:results.main.temp,
               humidity:results.main.humidity,
               desc:results.weather[0].description,
           })
        })
    }

    return(
        <div>
            <h1>Weather API</h1>
            <div>
                 Place:{info.name} <br/>
                 Temperature:{info.temp} <br/>
                 Humidity:{info.humidity} <br/>
                 Description: {info.desc}
            </div>
        </div>
    )
}

export default Home1;```

Can somebody help me to do this ?

【问题讨论】:

  • 问题是我想从用户那里获取位置,而不是在链接中提供硬编码

标签: html reactjs api


【解决方案1】:

您必须从用户那里获取输入并编写一个 onChange 事件处理程序。获得输入后,您可以调用 getWeather 函数并将您从用户那里获得的值传递给该函数。这是解决方案-

import React,{useState,useEffect} from 'react';

const Home1=()=>{
    const[info,setInfo]=useState({
        name:"loading !!",
        temp:"loading",
        humidity:"loading",
        desc:"loading",
    })

    const [inputValue , setInputValue] = useState("");
    useEffect(()=>
    {
        getWeather("chennai")
    })
    const getWeather=(value)=>
    {
        fetch(`http://api.openweathermap.org/data/2.5/weather?q=${value}&appid=bd2d67a73f2dc8279......`)
        .then(data=>data.json())
        .then(results=>{
           //console.log(results)
           setInfo({
               name:results.name,
               temp:results.main.temp,
               humidity:results.main.humidity,
               desc:results.weather[0].description,
           })
        })
    }

  const handleInputChange = event =>{
        let inputValue = event.target.value;
        console.log(event.target.value); // You will the value here. you can simply pass the value to the function
        setInputValue(inputValue);
        getWeather(inputValue);
    }

    return(
        <div>
            <h1>Weather API</h1>
            <div>
                 Place:{info.name} <br/>
                 Temperature:{info.temp} <br/>
                 Humidity:{info.humidity} <br/>
                 Description: {info.desc}
                 <input type="text" value={inputValue} onChange={handleInputChange} />
            </div>
        </div>
    )
}

export default Home1;

【讨论】:

  • 无法编译 src\components\APICALL.js 第 11:5 行:'handleChange' 未定义 no-undef 第 21:68 行:意外使用 'location' no-restricted-globals src\ components\stackoveripget.js Line 15:20: Unexpected use of 'location' no-restricted-globals 搜索关键字以了解有关每个错误的更多信息。
  • 在做handleInputChange时遇到这个错误
【解决方案2】:

您可以使用受控输入为用户提供选择位置的可能性。

const [city, setCity] = useState("chennai") // Initialize city default value

...

useEffect(()=> { getWeather(city) }, [city])
// Add the city as dependency to your effect and pass the value to getWeather method

...

fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=bd2d67a73f2dc8279......`)
// Make the url to fetch a template string so you can inject the city state in it

...

<input type="text" value={city} onChange={(e) => setCity(e.target.value)} />
// Add the input with onChange method

如果您想了解更多关于 React 中受控输入的信息,请参阅文档相关页面 https://reactjs.org/docs/forms.html

【讨论】:

  • 谢谢。但它在第一次正确加载。但是在输入字段中输入值后,它抛出错误未处理的拒绝(TypeError):无法读取未定义的属性'temp'如何处理此错误。你说的修改我已经修改了。
  • 是的,这是因为现在您每次用户更改输入时都会发出请求。对于某些值,天气数据不存在,“结果”变量返回 404 错误代码。请参阅文档 openweathermap.org/faq 中的“API 错误”。您必须处理该错误。在 setInfo 方法前加上 if 语句,检查响应的有效性
猜你喜欢
  • 2021-04-29
  • 2019-01-05
  • 2021-12-08
  • 2020-09-29
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 2022-01-18
  • 2021-12-28
相关资源
最近更新 更多