You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Snackbar/弹窗不显示问题排查与修复请求

问题:点击按钮无法触发Snackbar或alert提示

我希望点击按钮时能显示类似Snackbar或alert的弹窗提示,但目前点击按钮仅能正常展示选中的医生和日期,却无法触发Snackbar甚至alert提示,恳请帮忙修复该问题。

原代码

function Appointments({ onAppointmentSelection }) {

  const handleScheduleAppointment = (e) => {
    const appointment = {
      doctor: doctors.find((d) => d.name === doctor).name,
      appointmentDate: new Date(appointmentDate),
    };
    setAppointments([...appointments, appointment]);
    onAppointmentSelection(appointment);
    console.log('handleScheduleAppointment');
    alert("Appointment scheduled successfully!"); 
  };

  const handleCloseSnackbar = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }

    setShowSuccessMessage(false);
  };
  function formatDate(date) {
    const year = date.getFullYear();
    const month = `${date.getMonth() + 1}`.padStart(2, '0');
    const day = `${date.getDate()}`.padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  return (
    <div className='classes.root'>
      <Typography variant="h4" gutterBottom>
        Appointments
      </Typography>
      <form className='classes.form'>
        <Button
          variant="contained"
          color="primary"
          className='classes.button'
          disabled={!doctor || !appointmentDate}
          onClick={() => {
            handleScheduleAppointment();
            setShowSuccessMessage(true);
          }}
        >
          Schedule Appointment
        </Button>
      </form>
      <Snackbar
        open={showSuccessMessage}
        autoHideDuration={3000} // Hides the message after 5 seconds
        onClose={handleCloseSnackbar}
        message="Appointment scheduled successfully!"
        sx={{ bottom: '50px' }} // sets the position of the snackbar message
      />
    </div>
   )
}
export default Appointments;

问题分析与修复方案

你的代码存在几个关键问题,导致Snackbar和alert无法正常触发:

  1. 缺失必要的状态变量声明:

    • showSuccessMessage、appointments、doctor、appointmentDate这些状态都没有通过useState定义,React无法追踪状态变化,自然无法触发Snackbar的显示逻辑。
    • doctors变量也未在代码中声明,虽然你提到能正常展示医生信息,但需要确保它的存在(比如作为props传入或在组件内定义)。
  2. 函数调用参数不匹配:

    • handleScheduleAppointment定义了参数e,但点击事件中调用时未传递参数,不过这不会直接导致alert失效,但需要保持逻辑一致性。

修复后的完整代码

import { useState } from 'react';
import { Typography, Button, Snackbar } from '@mui/material';

function Appointments({ onAppointmentSelection, doctors }) {
  // 声明缺失的状态变量
  const [showSuccessMessage, setShowSuccessMessage] = useState(false);
  const [appointments, setAppointments] = useState([]);
  const [doctor, setDoctor] = useState(''); // 根据实际场景调整初始值
  const [appointmentDate, setAppointmentDate] = useState(''); // 根据实际场景调整初始值

  const handleScheduleAppointment = () => {
    // 确保选中的医生存在
    const selectedDoctor = doctors.find((d) => d.name === doctor);
    if (!selectedDoctor) return;

    const appointment = {
      doctor: selectedDoctor.name,
      appointmentDate: new Date(appointmentDate),
    };
    setAppointments([...appointments, appointment]);
    onAppointmentSelection(appointment);
    console.log('handleScheduleAppointment');
    alert("Appointment scheduled successfully!"); 
  };

  const handleCloseSnackbar = (event, reason) => {
    if (reason === 'clickaway') {
      return;
    }
    setShowSuccessMessage(false);
  };

  function formatDate(date) {
    const year = date.getFullYear();
    const month = `${date.getMonth() + 1}`.padStart(2, '0');
    const day = `${date.getDate()}`.padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  return (
    <div className='classes.root'>
      <Typography variant="h4" gutterBottom>
        Appointments
      </Typography>
      <form className='classes.form'>
        {/* 需补充医生选择、日期选择的UI组件,绑定对应状态 */}
        <Button
          variant="contained"
          color="primary"
          className='classes.button'
          disabled={!doctor || !appointmentDate}
          onClick={() => {
            handleScheduleAppointment();
            setShowSuccessMessage(true);
          }}
        >
          Schedule Appointment
        </Button>
      </form>
      <Snackbar
        open={showSuccessMessage}
        autoHideDuration={3000}
        onClose={handleCloseSnackbar}
        message="Appointment scheduled successfully!"
        sx={{ bottom: '50px' }}
      />
    </div>
   )
}
export default Appointments;

额外说明

  • 确保已导入useState和Material-UI的相关组件。
  • 需要补充医生选择、日期选择的UI组件(如Select、DatePicker),并绑定doctor、appointmentDate状态,否则按钮会一直处于禁用状态。
  • 如果doctors是外部数据,确保通过props传入组件。

内容的提问来源于stack exchange,提问作者user20886977

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:03:28