在React js中onClick之后状态不会立即更新

时间:2020-11-05 11:14:17

标签: reactjs

我正在单击复选框。当我选中复选框时,我正在尝试更新状态,但它不会立即更新。我创建了一个名为handleAllCheckbox的onchange事件。

这是我的代码- const [hello,setHello] = useState(false);

const handleAllCheckbox = (e) => {


    setHello(!hello);

    if (!hello) {
      contactList.map((item) => {
        Ids.push(item._id)
      });
      setTheArray(...theArray, Ids);
    }
    else {
      const newIds = []
      setTheArray(...theArray, newIds);
    }
  }

我想如果hellotrue,那么theArray必须有ID;如果为false,则theArray应该为空。

1 个答案:

答案 0 :(得分:1)

如果要处理任何副作用,则应使用useEffect,副作用意味着do something when a particular state change。因此,根据您的情况,可以参考以下内容

import { useState, useEffect } from 'react';

const [hello, setHello] = useState(false);

useEffect(() => {
  if (!hello) {
    contactList.map((item) => {
      Ids.push(item._id)
    });
    setTheArray(...theArray, Ids);
  }
  else {
    const newIds = []
    setTheArray(...theArray, newIds);
  }
}, [hello]);


const handleAllCheckbox = () => setHello(!hello);

[hello]作为useEffect的第二个参数,它表示do something whenever "hello" state is updated。因此,现在您的代码也变得更加简洁,handleAllCheckbox只关心处理状态hello,并且每当hello的值被更新时,useEffect都会处理此问题