reactjs 如何在react js中动态显示菜单项

balp4ylt  于 2022-12-18  发布在  React
关注(0)|答案(1)|浏览(157)

Here is the menu UI
尝试通过还原状态从后端动态加载菜单和菜单项。无法呈现特定菜单的菜单项。
json数据结构:

menuContext:{
  Define:[{id:1,label:"user"},{id:2,label:"test"}]
  Manage:[{id:1,label:"test2"},{id:2,label:"test3"}]
 }
function MenuContext() {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);

  const handleClick = (event) => {
    console.log(event.currentTarget)
    setAnchorEl(event.currentTarget);
  
  };
  const handleClose = () => {
    setAnchorEl(null);
  };
  const { viewService, isError, message } = useSelector(state => state.auth)
  const [menu, setMenu] = useState([])
  const [items, setItems] = useState([])
  const dispatch = useDispatch();
  useEffect(() => {
    return () => {
      console.log("cleaned up");
      dispatch(resetMenuContext())
      setMenu([])
    };
  }, []);

  useEffect(() => {
    if (viewService !== undefined) {
      if (viewService?.menuContext !== undefined) {
        const { menuContext } = viewService && viewService
        setMenu(menuContext)
     
      }
    }

  }, [viewService])

  return (
    <>
      {
 Object.entries(menu).map(([key, value]) => (
        <>

          <Button
            id={`button-${key}`}
            aria-controls={open ? `menu-${key}` : undefined}
            aria-haspopup="true"
            aria-expanded={open ? 'true' : undefined}
            variant="contained"
            disableElevation
            onClick={handleClick}
            endIcon={<KeyboardArrowDownIcon />}
            disableRipple
            style={{ textTransform: 'none' }}
          >
            {i18next.t(`label.${key}`)}
          </Button>

          <StyledMenu
            id={`menu-${key}`}
            MenuListProps={{
              'aria-labelledby': `button-${key}`,
            }}
            anchorEl={anchorEl}
            open={open}
            onClose={handleClose}
            key={key}
          >

            {
              Object.entries(value).map(({ id }) => (

                <MenuItem>
                  {id}
                </MenuItem>
              ))

            }

          </StyledMenu>

        </>

      ))

      }

    </>

  )
}

我需要做什么改变来显示每个菜单的菜单项。

htrmnn0y

htrmnn0y1#

值似乎是一个数组

{
          value?.map({ id, label }) => (
            <MenuItem key={id}>
              {label}
            </MenuItem>
          ))
      }

相关问题