我正在尝试将material-ui对话框的打开状态移至redux,以防止重新渲染发生时关闭它,但是在重新渲染发生时,对话框出现问题。尽管状态保存在redux中,并且每当发生重渲染时对话框都保持打开状态,但打开状态保持打开状态,但是对话框确实显示了打开动画(淡入),这有点烦人。
Students.js(模态的父组件)
const Students = ({
app: { studentsPage: { savedAddDialogOpen }},
setStudentsPageAddDialogOpen}) => {
// Create the local states
const [dialogOpen, setDialogOpen] = React.useState(savedAddDialogOpen);
const dialogOpenRef = React.useRef(savedAddDialogOpen);
// Change redux dialog open
const setReduxDialogState = () => {
setStudentsPageAddDialogOpen(dialogOpenRef.current, savedAddDialogOpen);
};
// Open add student dialog
const dialogClickOpen = () => {
setDialogOpen(true);
dialogOpenRef.current = true;
setTimeout(() => setReduxDialogState(), 300);
};
// Close add student dialog
const dialogClose = () => {
setDialogOpen(false);
dialogOpenRef.current = false;
setTimeout(() => setReduxDialogState(), 300);
};
return (
<Container>
{/* Add student modal */}
<AddStudentModal dialogOpen={dialogOpen} dialogClose={dialogClose} />
</Container>
)
}
// Set the state for this component to the global state
const mapStateToProps = (state) => ({
app: state.app,
});
AddStudentModal.js
const AddStudentModal = ({
dialogOpen, dialogClose
}) => {
return (
<Dialog
open={dialogOpen}
>
{/* Lots of stuff*/}
<DialogActions>
<Button onClick={dialogClose}>
Close dialog
</Button>
</DialogActions>
</Dialog>
)
};
我希望这足够了。我尝试检查是否在重新渲染时打开状态实际上是正确的,并且每次都正确,但是无论打开状态是什么,看起来对话框在重新渲染时都是关闭的,只有几毫秒之后才真正注意到它应该是开了
任何帮助将非常感激
编辑1:发现它与来自redux的打开状态无关,如果我使用open = {true},它仍然会闪烁,那么material-ui本身可能有问题吗?
编辑2:PrivateRoute.js
const PrivateRoute = ({
auth: { isAuthenticated, loadingAuth },
user: { loggedInUser },
component: Component,
roles,
path,
setLastPrivatePath,
...rest
}) => {
useEffect(() => {
if (path !== '/dashboard' && path !== '/profile') {
setLastPrivatePath(path);
}
// Prevent any useless errors with net line:
// eslint-disable-next-line
}, [path]);
// If we are loading the user show the preloader
if (loadingAuth) {
return <Preloader />;
}
// Return the component (depending on authentication)
return (
<Route
{...rest}
render={props =>
!isAuthenticated ? (
<Redirect to="/login" />
) : (loggedInUser && roles.some(r => loggedInUser.roles.includes(r))) ||
roles.includes('any') ? (
<Component {...props} />
) : (
<NotAuthorized />
)
}
/>
);
};
// Set the state for this component to the global state
const mapStateToProps = state => ({
auth: state.auth,
user: state.user
});
由于@RyanCogswell,我发现了问题!
对于任何有相同问题的人,这都是我的原因和解决方法:
我正在像这样将组件传递到Route组件中:
<PrivateRoute
exact
path={'/dashboard/students'}
component={(props) => (
<Students {...props} selectedIndex={selectedIndexSecondary} />
)}
roles={['admin']}
/>
通过这种方式,我可以通过我的privateRoute函数传递道具,但是如果您在常规Route组件中以这种方式发送组件,也会发生这种情况
对我来说,解决方案是将selectedIndexSecondary移至redux,然后以阻止重新安装的常规方式发送组件。
因此,仅这样做就可以防止这种情况的发生。
<PrivateRoute
exact
path={'/dashboard/students'}
component={Students}
roles={['admin']}
/>
同样,这将解决组件中的本地状态,从重置为默认值。所以对我来说,它解决了两个问题!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句