【问题标题】:Form input not updating API fetch表单输入未更新 API 获取
【发布时间】:2021-06-03 13:37:12
【问题描述】:

这是我的组件:

const WeatherData = () => {
const [city, setCity] = useState('')
const [unit, setUnit] = useState('imperial');
const [cardData, setCardData] = useState({});
function getForecast() {
    fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=${unit}&appid={hidden}`)
    .then(response => response.json())
    .then(response => setCardData(response))}

    return (
        <div>
        <form onSubmit={getForecast}>
            <input 
                placeholder='Enter City'
                value={city}
                onChange={(e) => setCity(e.target.value)}
            />
            <button type='submit'>Get Forecast</button>
        </form>
        </div>}

我的问题是,当我在输入中输入城市然后单击提交按钮时,它不会更新 getForecast 函数的 {city} 状态。怎么了?

【问题讨论】:

    标签: javascript reactjs use-state


    【解决方案1】:

    当您提交表单时,您会重新加载整个页面,这会取消 fetch 请求并将所有内容重置为默认值。

    捕获事件对象并阻止默认行为。

    function getForecast(e) {
        e.preventDefault();
        fetch...
    

    【讨论】:

      猜你喜欢
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      相关资源
      最近更新 更多