为什么更新后的状态没有返回到我的组件?

Why isn't the updated state returned to my component?

我有一个 drawer 用于我的移动导航,它可以正常打开,当我点击抽屉图标时也可以正常关闭。但我正在尝试实施 tap/click off 来关闭导航栏。因此,当用户单击或点击导航栏时,它应该关闭。但是当抽屉关闭时我收到了点击关闭的错误,因为页面中缺少 ref。所以我想用 运行 if (drawerIsOpen) { do...} else { dont...} 检查抽屉是否打开,奇怪的是我没有从我的道具收到更新的状态。抽屉可以正常关闭和打开,但是当我 console.log(drawerIsOpen) 它永远不会给出正确的状态。下面的代码应该可以解释我的一些意思。

const Drawer = ({ drawerIsOpen, handleDrawer, drawerButtonRef }) => {
  const drawerRef = useRef(null);

  function handleClickOutside(event) {
    if (!drawerIsOpen) {
      // always returns since state is always telling me the drawer is closed
      return;
    }
    if (drawerRef.current.contains(event.target)) {
      console.log('inside');
    } else {
      console.log('outside');
      console.log(handleDrawer);
      handleDrawer();
    }
}
useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('touchstart', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, []);

我的状态是通过道具发送的。我的状态从这个组件开始:

const drawerButtonRef = useRef(null);

const [drawerIsOpen, setDrawerIsOpen] = useState(false);
const handleDrawer = () => {
    setDrawerIsOpen((prevState) => !prevState);
};

return (
  <>
    <Drawer
        drawerIsOpen={drawerIsOpen}
        handleDrawer={handleDrawer}
        drawerButtonRef={drawerButtonRef}
     />
  </>
)

尝试将 drawerIsOpen 作为依赖项传递。您的 useEffect 逻辑仅被调用一次。

尝试以下方法:

useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('touchstart', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
    };
  }, [drawerIsOpen]);

drawerRef 也需要添加到您想要此行为的元素,否则它在您的逻辑中毫无意义。

Drawer 也没有 JSX 元素.....也许你忘了分享 post ?

你也可以简化这个

const handleDrawer = () => {
    setDrawerIsOpen((prevState) => !prevState);
};

对此

const handleDrawer = () => {
    setDrawerIsOpen(!drawerIsOpen);
};