ReactJS:Input 受控组件不改变状态

ReactJS:Input on controlled component doesn't change state

我有一个包含一些空值的对象文字,我想根据输入列表更改这些值。问题是,虽然输入的值在 useEffect() 中用预定义的值更新,但我无法使用 onChange 处理程序更改输入。这是我的:

const userValues = {
  username:'',
  city:'',
  country:'',
  description:''
}

function Comp(){
 const  [details, setDetails] = useState(userValues)

 useEffect(() => {
    setUserDetails()
  }, [details])

async function setUserDetails() {
      setDetails({...details,
      username: "username",
      country: "country",
      city: "city"
      })
}
const handleInputChange = (e) =>{
    const {name,value} = e.target
    setDetails({
      ...details,
      [name]:value
    })

   <Input fontSize="20px" w="sm" mr={5} fontWeight="bold" textAlign="center" 
               value={details.username} onChange={(e)=>handleInputChange(e)}/>
}

我也试过在onChange事件中直接设置值

onChange={(e)=>setDetails({...details,[e.target.name]:e.target.value})}} 

但输入不会改变默认值。也许有人可以指出我正确的方向。我遵循了本教程 https://dev.to/deboragaleano/how-to-handle-multiple-inputs-in-react-55el 任何帮助将不胜感激!

您必须为输入元素设置正确的 name 属性,例如:

  return (
    <Input

      name="userName"
      value={details.username}

      fontSize="20px"
      w="sm"
      mr={5}
      fontWeight="bold"
      textAlign="center"
      onChange={(e) => handleInputChange(e)}
    />
  )

第二期效果如下:

useEffect(() => {
    setUserDetails()
  }, [details])

每当 details 更改时,此代码将重置 details
您将必须删除此效果或至少从依赖项数组中删除 details 例如:

const  [details, setDetails] = useState(() => {
  return {
      username: "username",
      country: "country",
      city: "city"
  };
});

useEffect(() => {
    setUserDetails()
  }, [])