Material UI Snackbar仅首次弹出 后续消息无法重新打开问题求助
问题根源
- 自定义
Notification组件内部的状态没有和父组件传入的message属性同步:useState(message)的初始值仅在组件首次挂载时生效,后续父组件传入新的消息时,内部的value状态不会自动更新。 - 第一次Snackbar关闭时,你通过
onClose把内部value设为了空字符串,后续即便父组件传入新的message,内部value仍保持为空,导致open属性始终为false,Snackbar无法弹出。 - 给Snackbar设置
key={Math.random()}属于冗余逻辑,反而会引发不必要的组件重渲染,可直接删除。
修复方案
方案1:修改Notification组件,同步props变化
新增useEffect监听父组件传入的message属性,有新消息时自动更新内部状态:
import Snackbar from "@material-ui/core/Snackbar"; import { useState, useEffect } from "react"; export default function Notification({ message }) { const [value, setValue] = useState(message); // 同步父组件传入的新消息 useEffect(() => { if (message) { setValue(message); } }, [message]) return ( <Snackbar anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }} open={Boolean(value)} autoHideDuration={5000} message={value} onClose={() => { console.log('snackbar closed'); setValue('') }} /> ) };
方案2(更推荐):状态提升,使用受控组件
把Snackbar的显示控制权交给父组件,避免内部状态和外部属性不同步的问题:
- 改造Notification为受控组件:
import Snackbar from "@material-ui/core/Snackbar"; export default function Notification({ open, message, onClose }) { return ( <Snackbar anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }} open={open} autoHideDuration={5000} message={message} onClose={onClose} /> ) };
- 父组件新增状态控制Snackbar:
function InnerForm({ mode, detail, entity }) { // 原有逻辑不变 const isCreateMode = mode === 'create'; const schema = createSchema(entity); const { handleSubmit, formState: { errors }, control, setValue } = useForm({ defaultValues: detail, resolver: yupResolver(schema) }); const [submitResponse, setSubmitResponse] = useState(); // 新增Snackbar控制状态 const [snackbarOpen, setSnackbarOpen] = useState(false); const [snackbarMessage, setSnackbarMessage] = useState(''); const onSubmit = async data => { const operation = isCreateMode ? entity.Client.create(data) : entity.Client.update(data); const response = await operation; setSubmitResponse(response); // 设置Snackbar消息并打开 let msg = ''; if (response.success) { msg = 'operation completed'; if (isCreateMode) { const autoField = entity.Fields.find(({ auto }) => auto); if (autoField) { setValue(autoField.id, response.content[autoField.id]); } } } else if (response.problem) { msg = response.problem; } else { msg = 'operation failed'; } setSnackbarMessage(msg); setSnackbarOpen(true); }; return ( <> {/* 替换原有Notification渲染逻辑 */} <Notification open={snackbarOpen} message={snackbarMessage} onClose={() => setSnackbarOpen(false)} /> {/* 原有表单逻辑不变 */} <form onSubmit={handleSubmit(onSubmit)}> { entity.Fields.map(field => { const props = { control, id: field.id, label: field.label, error: errors[field.id]?.message, multiline: field.type === 'text', loadOptions: field.loadOptions, getOptionLabel: field.getOptionLabel, readonly: submitResponse?.success || field.auto || (field.key && !isCreateMode) }; const Component = field.type === 'string' ? TextInput : field.type === 'datetime' ? DatetimeInput : field.type === 'text' ? TextInput : field.type === 'entity' ? SelectInput : field.type === 'bool' ? CheckboxInput : TextInput; return <Component {...props} /> }) } <SubmitButton isCreateMode={mode === 'create'} readonly={submitResponse?.success} /> </form> </> ) }
内容的提问来源于stack exchange,提问作者optimusfrenk
相关产品推荐
相关产品推荐

