【问题标题】:Change useState Value everytime I enter Somthing in my Input每次在输入中输入 Something 时更改 useState 值
【发布时间】:2022-12-11 15:05:13
【问题描述】:

这是我正在处理的代码

所以,每次我改变我的输入时,我都希望状态改变,这将改变我的网址

但每次发生它都会显示错误

onKeyPress 是否有替代方案,因为它不起作用,我应该做些什么改变来实现它

“请阅读这段代码并告诉我如何控制台记录我的 URL 的 JSON”

import React,{useState} from 'react';
    import './App.css';
    import axios from 'axios';
    import Nav from "./components/Nav.js"

function App() {

  const {data,setData} = useState({})
  const {city,setCity} = useState('')

  const url = `http://api.weatherapi.com/v1/current.json?key=e893692528f845dfad844704220412&q=${city}&aqi=yes`


  function searchCity(event){
    if(event.key === 'Enter') {
      axios.get(url).then((response) => {
      setData(response.data)
      console.log(response.data)
    })
    }
  }






  return (
    <div >
      <Nav />
      <div className='form'>
            <input
            value={city}
            onChange={event => setCity(event.target.value)}
            onKeyPress = {searchCity}
            placeholder='Enter City'
            type="text"
            />
            

</div>
                  <div className="Container">
        <img src="./Img/top-japan-5.jpg" alt="Japan-as-weatherapp-top" className="main-img"/>

          
            
            <div  className="Temprature">12</div>
            <div  className="Location">Japan</div>
            <div  className="Weather">cloudy</div>
            <div  className="Humidity">Humidity</div>
            <div className="line"></div>
            <div  className="Wind">Wind</div>
            
            
          


        </div>
    </div>
  );
}

export default App;

错误信息

Uncaught TypeError: city is undefined
    handleChange App.js:25
    React 23
    js index.js:5
    factory react refresh:6
    Webpack 3

【问题讨论】:

标签: javascript reactjs api react-hooks


【解决方案1】:

useState 应该使用[]而不是{}

const [data,setData] = useState({})
const [city,setCity] = useState('')

将 url 包裹在 useMemo 周围

const url = useMemo(() => `http://api.weatherapi.com/v1/current.json?key=e893692528f845dfad844704220412&q=${city}&aqi=yes`, [city])

【讨论】:

    【解决方案2】:

    就在第一眼。您的useState 不正确。

    你有

    const {data,setData} = useState({})
    const {city,setCity} = useState('')
    

    但你需要

    const [data, setData] = useState({});
    const [city, setCity] = useState('');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2020-07-19
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多