简体   繁体   English

React.js:如何从表单提交更新 API 调用

[英]React.js: How to update API call from form submit

Making a weather app and I'm trying to update my api call on submit from a form.制作一个天气应用程序,我正在尝试从表单提交时更新我的​​ api 调用。 This is my first shot at making my own program and I've hit a block.这是我制作自己的程序的第一次尝试,但我遇到了障碍。 I'm setting my API call from useState, and the idea is the user types in the city, hits the button, and the API call runs again and displays the new data from the city.我正在从 useState 设置我的 API 调用,想法是用户在城市中键入,点击按钮,API 调用再次运行并显示来自城市的新数据。 I'm new to thinking as a programmer so I'm almost certain I'm missing something very simple.我是程序员的新手,所以我几乎可以肯定我错过了一些非常简单的东西。

import React, { useState, useEffect } from 'react';
import {Card} from 'react-bootstrap';
import Aux from '../../hoc/Aux';
// import classes from './wCard.css';
// import {Button} from 'react-bootstrap';


function WCard () {
        const [city,setCity] = useState('Queens');
        // const key = 'APP_KEY';
        const [feels_like,setFeelsLike] = useState('');
        const [mainTemp,setMainTemp] = useState('');
        const [description,setDescription] = useState('');
        const [main,setMain] = useState('');
        const [iconID,setIconID] = useState('');
        
        // useEffect(() => {
            


        const handleChange = (event) => {
            event.preventDefault()
            setCity(event.target.value)
        }

        const handleSubmit = (event) => {
            event.preventDefault()
            setCity(document.getElementsByName("city")[0].value)
            fetch(
                'https://api.openweathermap.org/data/2.5/weather?q=' + (city) + '&appid&units=imperial'
            )
                .then((res) => res.json())
                .then((data) => {
                    console.log(data);
                    setFeelsLike(data.main.feels_like);
                    setMainTemp(data.main.temp);
                    setDescription(data.weather[0].description);
                    setMain(data.weather[0].main);
                    setIconID(data.weather[0].icon);
                })
        },[city])
        
        
       
    return (
        <Aux>
            <div>
                <label>City</label>
                <form onSubmit={handleSubmit} >
                    <input type="text" placeholder="Ayyy" onChange={handleChange} />
                    <button type="submit">Weather time</button>
                </form>
            </div>

        <div style={{ display:'flex', justifyContent:'center', padding:'5em' }} >
            <Card style={{ width: '24rem', marginTop: '-3em' }}>
                <Card.Img variant="top" src={"http://openweathermap.org/img/wn/" + iconID + "@2x.png"} />
                <h1 style={{ textAlign:'center', color:'#00BFFF' }} >{city}</h1>
                <Card.Body>
                    <Card.Title>{mainTemp}°, feels like {feels_like}°</Card.Title>
                    <Card.Text style={{ textTransform:'capitalize' }} >
                    {description}
                    </Card.Text>
                </Card.Body>
            </Card>
            </div>
        </Aux>
    )    
}

export default WCard;

I believe your useEffect isn't being called again, since you passed in a [] as your array of dependencies.我相信您的 useEffect 不会再次被调用,因为您传入了 [] 作为您的依赖项数组。 Try doing useEffect(..., [city]) .尝试做useEffect(..., [city]) That way, useEffect will be called on update of city这样, useEffect 将在city更新时被调用

in

const handleSubmit = (event) => {
            event.preventDefault()
            setCity(event.target.value.city)
            
        }

There is a typo.有一个错字。 It should be event.target.value not event.target.value.city它应该是 event.target.value 而不是 event.target.value.city

And there is no need to have the onChange method.并且不需要 onChange 方法。

And as you now know from what Victor said, useEffect will get called if the given dependency changes.正如你现在从 Victor 所说的那样,如果给定的依赖项发生变化, useEffect 将被调用。

use this on useEffect在 useEffect 上使用它

useEffect(..., [city])

and in handleSubmit there is the problem that event.target is where the click has been triggered, so in this case, the button, you must target the input而在handleSubmit中存在的问题是event.target是点击被触发的地方,所以在这种情况下,按钮,你必须针对输入

const handleSubmit = (event) => {
        event.preventDefault()
        setCity(document.getElementsByName("city")[0].value)
    }

the rest of the code is ok其余的代码没问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM