如何修复隐藏时MUI小吃条/烤面包闪烁



我正试图在点击按钮时显示Snackbar/Tast,并在几秒钟后取消抑制。问题是,当Snackbar解除抑制时,Snackbar会闪烁而不显示文本。如何解决?

下面是codesandbox来了解我的意思:https://codesandbox.io/s/elastic-haibt-id7bfg?file=/demo.tsx:601-1510

切片:

const initialState: CommonState = {
alert: {
isOpen: false,
type: AlertType.Info,
message: ""
}
};
const commonSlice = createSlice({
name: "common",
initialState,
reducers: {
showAlert: (state, action: PayloadAction<Alert>) => {
state.alert = action.payload;
},
hideAlert: (state) => {
state.alert = null;
}
}
});

组件

export default function App() {
const dispatch = useDispatch<AppDispatch>();
const { alert } = useSelector((state: RootState) => state.common);
const handleShowAlert = () => {
dispatch(
showAlert({
isOpen: true,
type: AlertType.Success,
message: "Text copied message"
})
);
};
const handleHideAlert = () => {
dispatch(hideAlert());
};
return (
<Stack spacing={2} sx={{ width: "100%" }}>
<Button onClick={handleShowAlert}>Show Alert</Button>
<Snackbar
open={alert?.isOpen}
autoHideDuration={3000}
onClose={handleHideAlert}
anchorOrigin={{ vertical: "top", horizontal: "center" }}
>
<Alert
onClose={handleHideAlert}
severity={alert?.type}
sx={{ width: "100%" }}
>
{alert?.message}
</Alert>
</Snackbar>
</Stack>
);
}

Snackbar在没有文本的情况下闪烁,因为hideAlert操作已将alert更改为null
因此,alert?.message变为undefined(没有文本(。

您可以通过将alertisOpen更改为false来修复它,并将消息保留在hideAlert操作中。

hideAlert: (state) => {
state.alert = {
...state.alert,
isOpen: false
};
}

最新更新