提问人:Imaginario27 提问时间:9/4/2023 最后编辑:Imaginario27 更新时间:9/4/2023 访问量:19
如何防止重复调用包含 toastify 通知的多个子组件实例?
How to prevent duplicates calling mutiple child component instances that includes toastify notifications?
问:
我正在使用多个 toast 组件实例,在每种情况下传递不同的参数。
当用户单击特定按钮以显示某种类型的 Toast 时,它会出现重叠 4 次。
这是代码:
import Toast from "../toasts/Toast"
export default function ToastSection (){
return (
<section>
<h2>Toasts</h2>
<h3>With image</h3>
<div className="toasts">
<Toast
type="info"
title = "Information"
message="Please read updated information"
id={1}
/>
<Toast
type= "success"
title = "Success"
message="Your work has been saved"
id={2}
/>
<Toast
type= "warn"
title = "Warning"
message="A network error was detected"
id={3}
/>
<Toast
type= "error"
title = "Error"
message="Please re-save your work again"
id={4}
/>
</div>
</section>
)
}
/* eslint react/prop-types: 0 */
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
export default function Toast (
{
type = "",
title = "Example title",
message = "This is an example message",
id
}
){
const toastParameters = {
position: 'top-right',
autoClose: 2000,
hideProgressBar: true,
closeOnClick: false,
pauseOnHover: false,
draggable: false,
className: `toast ${type}`
}
function Message() {
return (
<div>
<p className="toast-title">{title}</p>
<p className="toast-message">{message}</p>
</div>
)
}
function showToast() {
// Check if the toast with the same identifier is already active
const existingToast = toast.isActive(id);
// If a toast with the same identifier exists, don't show a new one
if (!existingToast) {
if (type === "info") {
toast.info(Message, { ...toastParameters, toastId:id })
}
else if (type === "success") {
toast.success(Message, { ...toastParameters, toastId:id })
}
else if (type === "warn") {
toast.warn(Message, { ...toastParameters, toastId:id })
}
else if (type === "error") {
toast.error(Message, { ...toastParameters, toastId:id })
}
else {
toast(Message, { ...toastParameters, toastId:id })
}
}
}
return (
<>
<button className={type} onClick={showToast}>
{type}
</button>
<ToastContainer />
</>
)
}
每个按钮显示一种通知类型。
我只想显示每个通知一次,而不是每个通知重叠 4 次。
答: 暂无答案
评论