如何在 mui v5 Snackbar 中动态创建多个警报

Moe*_*Moe 4 javascript typescript reactjs material-ui react-hooks

我正在调用 API 来执行一些操作。
我想获取每个操作的响应并将其显示在 Snackbar/alert 中。

即使在迭代地图中的消息之后,我也只能显示第一个响应,而不能显示其他内容。

这是我调用 api 的业务逻辑

try {
      const deletedUser = await deleteUser({ username: username });
      [deletedUser.data.status.action1, deletedUser.data.status.action2].map(
        (msg) =>
          setNotify({
            isOpen: true,
            message: msg,
            type: "success",
          })
      );
    } catch (error) {}
Run Code Online (Sandbox Code Playgroud)

setNotify 将打开带有警报的 Snackbar

import React from "react";
import { Snackbar, Alert } from "@mui/material";

import { styled } from "@mui/material/styles";

const StyledSnackbar = styled((props) => <Snackbar {...props} />)(
  ({ theme }) => ({
    "& .MuiSnackbar-root": {
      top: theme.spacing(15),
    },
  })
);

export default function Notification(props) {
  const { notify, setNotify } = props;
  const handleClose = (event, reason) => {
    setNotify({
      ...notify,
      isOpen: false,
    });
  };
  return (
    <StyledSnackbar
      open={notify.isOpen}
      autoHideDuration={10000}
      anchorOrigin={{ vertical: "top", horizontal: "right" }}
      onClose={handleClose}
    >
      <Alert severity={notify.type} onClose={handleClose}>
        {notify.message}
      </Alert>
    </StyledSnackbar>
  );
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是它只显示第一个操作而没有其他内容。

在沙盒上编辑

我怀疑警报相互重叠也许我们需要添加某种 AutoGrow 属性

Fra*_*ion 7

您必须按照MUI 文档notistack中的描述使用:

此示例演示如何使用notistack。notistack 有一个 命令式 API,可以轻松显示小吃栏,而无需处理其打开/关闭状态。它还使您能够将它们堆叠在一起(尽管 Material Design 指南不鼓励这样做)。

首先将您的应用程序包装在SnackbarProvider组件内,然后使用useSnackbar钩子进行访问enqueueSnackbar,以便将小吃栏添加到要显示的队列中:

应用程序.js

import "./styles.css";
import React from "react";
import { SnackbarProvider } from "notistack";
import Notification from "./Notification";

export default function App() {
  return (
    <SnackbarProvider maxSnack={3}>
      <div className="App">
        <h1>Dynamic Snackbar Alerts</h1>
        <Notification />
      </div>
    </SnackbarProvider>
  );
}
Run Code Online (Sandbox Code Playgroud)

通知.js

import React from "react";
import { Button } from "@mui/material";
import { useSnackbar } from "notistack";

export default function Notification(props) {
  const { enqueueSnackbar } = useSnackbar();

  const handleClick = async () => {
    try {
      const deletedUser = await deleteUser({ username: username });
      [deletedUser.data.status.action1, deletedUser.data.status.action2].forEach((msg) => {
          enqueueSnackbar(msg, {
            variant: "success",
            autoHideDuration: 10000,
            anchorOrigin: { vertical: "top", horizontal: "right" }
          });
      });
    } catch (error) {}
  };

  return (
    <Button variant="outlined" onClick={handleClick}>
      Generate Snackbar Dynamicly
    </Button>
  );
}
Run Code Online (Sandbox Code Playgroud)

演示:

编辑 Sparkling-moon-ikm0o