【发布时间】:2021-06-16 12:55:16
【问题描述】:
我正在使用 Material-UI 框架中的 Snackbar 组件,但我无法使其正常工作,因为 Snackbar 仅第一次显示,从第二条消息开始,Snackbar 保持关闭。
这是我用来包装 Snackbar 的代码:
import Snackbar from "@material-ui/core/Snackbar";
import { useState } from "react";
export default function Notification({ message }) {
const [value, setValue] = useState(message);
return (
<Snackbar
key={Math.random()}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center'
}}
open={value ? true : false}
autoHideDuration={5000}
message={value}
onClose={() => { console.log('snackbar closed'); setValue('') }}
/>
)
};
当用户提交表单时,我使用这个组件来显示结果。例如,当提交成功时,会显示消息“操作已完成”,但如果服务器未验证提交,则会显示消息错误。代码如下:
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();
const onSubmit = async data => {
const operation = isCreateMode ?
entity.Client.create(data) :
entity.Client.update(data);
const response = await operation;
setSubmitResponse(response);
console.log(response);
if (response.success) {
if (isCreateMode) {
const autoField = entity.Fields.find(({ auto }) => auto);
if (autoField) {
setValue(autoField.id, response.content[autoField.id]);
}
}
}
};
return (
<>
{
submitResponse ?
submitResponse.success ?
<Notification message='operation completed' /> :
submitResponse.problem ?
<Notification message={submitResponse.problem} /> :
<Notification message='operation failed' />
: null
}
<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>
</>
我做的测试如下:
- 首先,我用无效数据编译表单并执行提交 => 好的,snackbar 出现错误消息。
- 其次,我更正数据,执行新的提交=> 提交成功,但是没有显示成功信息
【问题讨论】:
标签: reactjs material-ui