【问题标题】:setCity is not a function error at consolesetCity 不是控制台的函数错误
【发布时间】:2023-01-26 16:04:56
【问题描述】:

我的目标是在输入时同时在控制台上显示字母。但是每按一个字母就突然报错看这张图:enter image description here

我相信我的编码有问题。你能检查一下吗?

import {useState, useEffect} from "react";



const Form = () => {
    const [city, setCity]= useState=('');
 
    useEffect( () => console.log(city) ,[city] );

    const handleChange = () => {
    } 

    return (

        <div className="form">
            <h1 className="h1">Weather App</h1>
            <form onSubmit={(e)=> {e.preventDefault(); handleChange()}}>
                <div className='form2'>
                    <input  onChange={(e)=> setCity(e.target.value)}  className='inputText' type='text' placeholder="Enter the city" />
                </div>
                <div className='btnDiv'>
                    <button type="submit" className="btn">Enter</button>
                </div>
            </form>
        </div>
    )


}
export default Form;

我相信我的状态有问题。

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    您的“useState”行是错误的。 您应该删除 useState 和 ('') 之间的“=” 医生:https://reactjs.org/docs/hooks-state.html

    【讨论】:

      【解决方案2】:

      我看到的第一个错字是: const [city, setCity]= useState=('');

      应该: const [city, setCity]= useState('');

      【讨论】:

        【解决方案3】:

        您为“城市”设置初始状态的方式似乎存在问题。您应该使用"useState('')",而不是使用"useState=()"。此外,您还没有在 handleChange() 函数中实现任何在表单提交时调用的函数。请尝试以下操作。

        const Form = () => {
            const [city, setCity] = useState('');
        
            useEffect( () => console.log(city) ,[city] );
        
            const handleChange = (e) => {
                e.preventDefault();
                console.log(city);
            } 
        
            return (
        
                <div className="form">
                    <h1 className="h1">Weather App</h1>
                    <form onSubmit={handleChange}>
                        <div className='form2'>
                            <input  onChange={(e)=> setCity(e.target.value)}  className='inputText' type='text' placeholder="Enter the city" />
                        </div>
                        <div className='btnDiv'>
                            <button type="submit" className="btn">Enter</button>
                        </div>
                    </form>
                </div>
            )
        
        
        }
        export default Form;
        

        【讨论】:

          猜你喜欢
          • 2017-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-03
          • 2017-02-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多