我有一个react next.js项目和一个表单。我想在表单中使用滑块。顺便说一句,我使用语义ui反应。我有一个useState钩,输入以下内容:
function CreateTicket() {
const [ticket, setTicket] = useState({
name: "",
description: "",
media: "",
priority: false
});
....
和handleChange,handleSubmit和handleToggle函数。当我在console.log中提交表单时,不要将priority的值设置回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}
我怎么了?
答案 0 :(得分:3)
您需要将priority
上的prevState
解构,而不是event.target
:
const handleToggle = event => {
setTicket(({ priority, ...prevState }) =>
({ ...prevState, priority: !priority })
);
};
作为一种优化,您可以使用handleToggle
来记住useCallback()
,这样<Checkbox/>
不需要每次状态更新时都重新渲染:
const handleToggle = useCallback(event => {
setTicket(({ priority, ...prevState }) =>
({ ...prevState, priority: !priority })
);
}, [setTicket]);