当输入值是文本字段中的变化时,请立即恢复问题

发布于 2025-02-08 11:33:42 字数 3151 浏览 0 评论 0 原文

我的应用程序依赖“城市”值来调用API并接收数据栏,为此,我设置了一张表格,使其在我的城市使用setState值,并在我的主应用程序上使用使用效率值。曼城是通过意见提交的,它将养育。问题在于,一旦更改了输入的文本,setCity函数立即关闭,并且不等待提交功能。有帮助吗?

import * as React from 'react';
import '../cssdirect/App.css'
import Icon from './Icon'
import Wind from './Wind'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faDroplet } from '@fortawesome/free-solid-svg-icons'
import { faArrowRight } from '@fortawesome/free-solid-svg-icons'
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import PinDropIcon from '@mui/icons-material/PinDrop';
import { useState, useEffect } from 'react';
const Daily = ({coord, weather, main, visibility, wind, clouds, sys, timezone, name, dt, setCity, city}) => {
    const [time, setTime] = useState('')

    function timeConverter(dt){
        var a = new Date(dt * 1000);
        var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        var year = a.getFullYear();
        var month = months[a.getMonth()];
        var date = a.getDate();
        var hour = a.getHours();
        var time = date + ' ' + month + ' ' + year + ' ' + hour;
        return time;
      }
      const handleSubmit = (e) =>{
        e.preventDefault()
        console.log(city) 
      }      

      useEffect(()=>{
        setTime(timeConverter(dt))
      },[])
  return (
    <>
            <h1 className='title'>Monkey Wit Da Weather</h1>
            <div className="textInput" 
            onSubmit={handleSubmit}>
            <TextField id="outlined-basic" 
            placeholder='city'  
            name='city' 
            type="text" 
            onSubmit={(event)=>setCity(event.target.value)} 
            value={city}
            InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <PinDropIcon/>
            </InputAdornment>
          ),
        }} variant="standard" />
        <button className="submit" onClick={handleSubmit} type="submit"><FontAwesomeIcon icon={faArrowRight} /></button>    
        </div>
          
    </>
  )
}

export default Daily

app.js

import './cssdirect/App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
import Loading from './Loading';

function App() {
const [loading, setLoading] = useState(true)
const [city, setCity] = useState('Forest%20Hills')
const [weatherData, setWeather] = useState([])


const getWeather = async() =>{
  setLoading(true)
  try{
    const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=f8d957da06af592a1390c360ea801908&units=imperial`)
    const pResp = await resp.json()
    setWeather(pResp)
    setLoading(false)
  }
  catch{
    console.log('error')
  }
}

useEffect(()=>{
  getWeather()
},[city])

  if(loading==true){
    return <Loading/>
  }
  else{
    return <Daily {...weatherData} setCity={setCity} city={city}/>
  }
}

export default App;

My application relies on the 'city' value to call an API and receive databack, for that, I set up a form made it use a setState value on my city, and a useEffect value on my main App.js so every time a new city was submitted through the input, it would rerender. The issue is that the setCity function goes off immediately as soon as the text inside the input is changed and does not wait for the submit function. Any help ?

import * as React from 'react';
import '../cssdirect/App.css'
import Icon from './Icon'
import Wind from './Wind'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faDroplet } from '@fortawesome/free-solid-svg-icons'
import { faArrowRight } from '@fortawesome/free-solid-svg-icons'
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import PinDropIcon from '@mui/icons-material/PinDrop';
import { useState, useEffect } from 'react';
const Daily = ({coord, weather, main, visibility, wind, clouds, sys, timezone, name, dt, setCity, city}) => {
    const [time, setTime] = useState('')

    function timeConverter(dt){
        var a = new Date(dt * 1000);
        var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        var year = a.getFullYear();
        var month = months[a.getMonth()];
        var date = a.getDate();
        var hour = a.getHours();
        var time = date + ' ' + month + ' ' + year + ' ' + hour;
        return time;
      }
      const handleSubmit = (e) =>{
        e.preventDefault()
        console.log(city) 
      }      

      useEffect(()=>{
        setTime(timeConverter(dt))
      },[])
  return (
    <>
            <h1 className='title'>Monkey Wit Da Weather</h1>
            <div className="textInput" 
            onSubmit={handleSubmit}>
            <TextField id="outlined-basic" 
            placeholder='city'  
            name='city' 
            type="text" 
            onSubmit={(event)=>setCity(event.target.value)} 
            value={city}
            InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <PinDropIcon/>
            </InputAdornment>
          ),
        }} variant="standard" />
        <button className="submit" onClick={handleSubmit} type="submit"><FontAwesomeIcon icon={faArrowRight} /></button>    
        </div>
          
    </>
  )
}

export default Daily

App.js

import './cssdirect/App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
import Loading from './Loading';

function App() {
const [loading, setLoading] = useState(true)
const [city, setCity] = useState('Forest%20Hills')
const [weatherData, setWeather] = useState([])


const getWeather = async() =>{
  setLoading(true)
  try{
    const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=f8d957da06af592a1390c360ea801908&units=imperial`)
    const pResp = await resp.json()
    setWeather(pResp)
    setLoading(false)
  }
  catch{
    console.log('error')
  }
}

useEffect(()=>{
  getWeather()
},[city])

  if(loading==true){
    return <Loading/>
  }
  else{
    return <Daily {...weatherData} setCity={setCity} city={city}/>
  }
}

export default App;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光①夏 2025-02-15 11:33:42

是的,这应该是您编码的行为,因为您使用使用 city 作为触发 getweather 的依赖性异步函数(在 app.js 中检查以下代码)。每当 City 状态在重新渲染期间发生变化时,就会发生这种触发。

useEffect(()=>{
  getWeather()
},[city])

您需要的是触发 getweather async函数进行提交时,而不是更改 City 时。因此,将 getweather async函数传递给儿童组件( daily )作为道具,并在 handleseubmit 中称其为以下内容。

      const handleSubmit = (e) =>{
        e.preventDefault()
        console.log(city) 
        getWeather()
      }   

此外,还要删除前面提到的使用效果

顺便说一句,我认为如果您使用 onChange 事件,而不是 onsubmit 内部 textfield 来自材料UI的组件,则更好。 (参考

<TextField
  id="outlined-basic"
  placeholder="city"
  name="city"
  type="text"
  onChange={(event) => setCity(event.target.value)}
  value={city}
  InputProps={{
    startAdornment: (
      <InputAdornment position="start">
        <PinDropIcon />
      </InputAdornment>
    ),
  }}
  variant="standard"
/>;

Yes, it should be the behavior the way you coded, because you're using an useEffect with city as the dependency on it to trigger getWeather async function (check the below code in App.js). This trigger happens whenever city state changes during re-rendering.

useEffect(()=>{
  getWeather()
},[city])

What you need is to trigger the getWeather async function when you do the submission, not when you change city. Therefore, pass getWeather async function to child component (Daily) as a prop and call it inside the handleSubmit as follows.

      const handleSubmit = (e) =>{
        e.preventDefault()
        console.log(city) 
        getWeather()
      }   

And additionally, remove the previously mentioned useEffect as well.

By the way, I think it's better if you use onChange event instead of onSubmit inside TextField component from material UI. (reference)

<TextField
  id="outlined-basic"
  placeholder="city"
  name="city"
  type="text"
  onChange={(event) => setCity(event.target.value)}
  value={city}
  InputProps={{
    startAdornment: (
      <InputAdornment position="start">
        <PinDropIcon />
      </InputAdornment>
    ),
  }}
  variant="standard"
/>;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文