为什么 useState 仅在您第二次单击按钮时才设置数据?

时间:2021-03-02 13:01:02

标签: javascript reactjs material-ui use-state

我尝试在 useState 中设置值,但是只有当我第二次单击该按钮时才起作用,为什么会发生这种情况?

const DropDownMenu = ({ element, segmentEnd, segmentStart }) => {
  const [open, setOpen] = React.useState(false);
  const [ratio, setRatio] = React.useState("");

  const handleToggle = () => {
    setOpen((prevOpen) => !prevOpen);
  };
  const handleClose = () => {
    setOpen(false);
  };
  const openFitToScreen = () => {
    setRatio("Fit to screen");
    setOpen(false);
  };

  const openFitToHeight = () => {
    setRatio("Fit to height");
    setOpen(false);
  };

  const openFitToWidth = () => {
    setOpen(false);
    setRatio("Fit to width");
  };

  const openOriginal = () => {
    setOpen(false);
    setRatio("Original");
  };

  return (
    <Box style={{ display: "flex" }}>
      <Box>
        <Box onClick={handleToggle} style={{ cursor: "pointer" }}>
          {ratio !== "" ? ratio : element.ratio}
        </Box>
        <Popper
          open={open}
          role={undefined}
          transition
          disablePortal
          style={{ position: "absolute", top: 20, zIndex: 1000 }}
        >
          {({ TransitionProps, placement }) => (
            <Grow
              {...TransitionProps}
              style={{
                transformOrigin:
                  placement === "bottom" ? "center top" : "center bottom",
              }}
            >
              <Paper>
                <ClickAwayListener onClickAway={handleClose}>
                  <MenuList autoFocusItem={open} id="menu-list-grow">
                    <MenuItem value="Original" onClick={() => openOriginal()}>
                      Original
                    </MenuItem>
                    <MenuItem
                      value="Fit to screen"
                      onClick={() => openFitToScreen()}
                    >
                      Fit to screen
                    </MenuItem>
                    <MenuItem
                      value="Fit to height"
                      onClick={() => openFitToHeight()}
                    >
                      Fit to height
                    </MenuItem>
                    <MenuItem
                      value="Fit to width"
                      onClick={() => openFitToWidth()}
                    >
                      Fit to width
                    </MenuItem>
                  </MenuList>
                </ClickAwayListener>
              </Paper>
            </Grow>
          )}
        </Popper>
      </Box>
    </Box>
  );
};

我尝试在 useState 中设置值,但是只有当我第二次单击该按钮时才起作用,为什么会发生这种情况? 我试图在useState中设置值,但只有当我第二次单击按钮时才起作用,为什么会发生这种情况?

2 个答案:

答案 0 :(得分:0)

第二次设置哪个值?

useCallBack(() => <Popper>....</Popper>, [open])

答案 1 :(得分:-1)

我不明白你为什么这样做:

  const handleToggle = () => {
    setOpen((prevOpen) => !prevOpen); // your state need to be a boolean not a function
  };

而是尝试这样做:

  const handleToggle = () => {
    setOpen(!prevOpen);
  };