首页 > 解决方案 > useState 在需要时不会改变

问题描述

用户必须在表格中输入姓名和医院,然后他们的姓名和医院将出现在侧面菜单中。但我做不到,useState 返回一个空状态,所以它不起作用

export function Home() {
 
  const [nome, setNome] = useState("")
  const [hospital, setHospital] = useState("")
  const [describe, setDescribe] = useState("")
  const [patient, setNewPatient] = useState({})

  
  
  function handleCreateNewPatient(event){
    event.preventDefault()
    
    setNewPatient({
      id: nome.length,
      nome: nome,
      hospital: hospital,
      describe: describe
    })

    Users.push(patient)
    
  }

带有表单的 UI 材料的代码

<form onSubmit={handleCreateNewPatient} >
             <div>
               <TextField
                 value={nome}
                 onChange={event=>setNome(event.target.value)}
               />
               <TextField
                 value={hospital}
                 onChange={event=>setHospital(event.target.value)}
               />
             </div>
             <div>
               <TextareaAutosize
               value={describe} 
               onChange={event=>setDescribe(event.target.value)}
            />
             </div>
             <Button type="submit">Confirmar</Button>
           </form>

标签: reactjsreact-hooks

解决方案


问题在这里:

setNewPatient({
      id: nome.length,
      nome: nome,
      hospital: hospital,
      describe: describe
    })

    Users.push(patient)

setState() 是异步的。React 不保证立即应用状态更改。将 setState() 视为更新组件的请求而不是立即命令。

要获得更新的值,您必须使用useEffect如下:

useEffect(() => {
    if( patient.hasOwnProperty('id') )  // Checking if patient is set or not
    {
        Users.push(patient)
    }
}, [patient]);  // Here `patient` is the dependency so this effect will run every time when `patient` change.

这种类型的逻辑会帮助你。


推荐阅读