简体   繁体   English

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

[英]How to dynamically create multiple alerts inside mui v5 Snackbar

I am calling an API to do few actions.我打电话给 API 做一些动作。
I want to take the response of each action and show it inside Snackbar/alert.我想获取每个动作的响应并将其显示在 Snackbar/alert 中。

I am able to show only the first response and nothing else even after iterating the messages in a map.即使在迭代 map 中的消息后,我也只能显示第一个响应,而不能显示其他任何内容。

Here is my business logic calling the api这是我调用 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) {}

setNotify will open the Snackbar with the alerts 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>
  );
}

The only issue it's only displaying the first action and nothing else.唯一的问题是它只显示第一个动作,没有别的。

Edit On Sandbox在沙盒上编辑

I suspect the alerts are overlapping on top of each other Maybe we need to add some sort of AutoGrow prop我怀疑警报相互重叠也许我们需要添加某种 AutoGrow 道具

You have to use notistack as described in the MUI doc :您必须按照MUI doc中的说明使用notistack

This example demonstrates how to use notistack .这个例子演示了如何使用notistack notistack has an imperative API that makes it easy to display snackbars, without having to handle their open/close state. notistack 有一个命令式 API ,可以轻松显示小吃吧,而无需处理它们的打开/关闭 state。 It also enables you to stack them on top of one another (although this is discouraged by the Material Design guidelines).它还使您能够将它们堆叠在一起(尽管 Material Design 指南不鼓励这样做)。

Start by wrapping your app inside a SnackbarProvider component then use useSnackbar hook to access to enqueueSnackbar in order to add a snackbar to the queue to be displayed:首先将您的应用程序包装在SnackbarProvider组件中,然后使用useSnackbar钩子访问enqueueSnackbar以便将小吃栏添加到要显示的队列中:

App.js应用程序.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>
  );
}

Notification.js通知.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>
  );
}

Demo:演示:

编辑 sparkling-moon-ikm0o

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM