useState与布尔值

时间:2019-11-20 19:27:35

标签: reactjs react-hooks next.js

我有一个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}

我怎么了?

1 个答案:

答案 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]);