不要在Form.Control中设置值



我有一个用于保存数据的新表单。

我使用这个代码

const [validated, setValidated] = useState(false);
const [newInfo, setNewInfo] = useState({
name: ""
});
const handleChange = (event) => {
const { name, value }=event.target.value;
setNewInfo({
...newInfo,
[name]: value
});
console.log(newInfo.name)
};

以及在Form.Control 中

<Form noValidate validated={validated}>
<Form.Group >
<Form.Label>Name</Form.Label>
<Form.Control required type="text" placeholder="Enter Name" value={newInfo.name}
onChange={handleChange} />
<Form.Control.Feedback type="invalid">Please choose a name.</Form.Control.Feedback>
</Form.Group>
<Button onClick={(e) => handleSubmit(e)} variant="primary">Submit</Button>
</Form>

当我输入输入时,运行onchangehandle,event.target.value有值,但没有在输入中设置(输入为空(!!

当我更改const [newInfo, setNewInfo] = useState("");并为其设置字符串时,它是可以的。

setNewInfo ((是一个setter,它是异步的,这意味着在您控制台日志状态时,它还没有更新。

您可以使用useEffect来跟踪状态的变化

useEffect(() => {
console.log(newInfo);
},[newInfo.name);