reactjs - 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>
解决方案
问题在这里:
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.
这种类型的逻辑会帮助你。
推荐阅读
- laravel - 如何将此查询转换为 Laravel ORM
- c# - SCIM 端点。从 Azure AD 测试时出错
- python-3.x - 在 keras 中连接两个嵌入层会引发 ValueError
- reactjs - React:如何从子组件更新数组中的对象
- flutter - 在警报框被解除后运行一个函数
- php - 具有特定键和条件的 PHP 数组总和
- c - 如何将文件的一部分扫描为变量
- google-cloud-platform - 包含“#”的 Google 负载均衡器映射 url
- batch-file - 如何使用“批处理”移动重音文件?
- reactjs - 如何将数据数组传递给 Typescript React 组件并在其中使用它?