我有一个react next.js项目和一个表单。我想在表单中使用滑块。顺便说一下,我使用语义ui react。我有一个useState钩子,输入如下:
function CreateTicket() {
const [ticket, setTicket] = useState({
name: "",
description: "",
media: "",
priority: false
});
....
以及handleChange、handleSubmit和handleToggle函数。当我在console.log中提交表单时,它不会将优先级值设置回false。
<Checkbox
style={{ padding: "1rem" }}
label="Important?"
name="priority"
toggle
onChange={handleToggle}
/>
const handleToggle = event => {
let { priority } = event.target;
setTicket(prevState => ({ ...prevState, priority: !priority }));
};
console.log->
页面刷新后:
{name: "", description: "", media: "", priority: false}
之后:切换
{name: "", description: "", media: "", priority: true}
在第二次触发之后
{name: "", description: "", media: "", priority: true}
我做错了什么?
您需要从prevState
而不是event.target
:中销毁priority
const handleToggle = event => {
setTicket(({ priority, ...prevState }) =>
({ ...prevState, priority: !priority })
);
};
作为优化,您可以使用useCallback()
来存储handleToggle
,这样<Checkbox/>
就不需要在每次状态更新时重新渲染:
const handleToggle = useCallback(event => {
setTicket(({ priority, ...prevState }) =>
({ ...prevState, priority: !priority })
);
}, [setTicket]);