如何防止nextjs上组件卸载/重新挂载

问题描述 投票:0回答:1

在我的 nextjs 14 应用程序中,我有一个不应卸载/重新安装的聊天组件。问题是,在我的移动屏幕上,我创建了一个展开聊天的按钮和一个关闭聊天的按钮。当我展开/关闭聊天时,该组件将被销毁并重新渲染,并且我会失去对话。有没有办法避免这种情况发生?

这是我的代码:

//Brakpoints
    const FirstRoot = styled(Paper)(({ theme }) => ({
      marginInline: theme.spacing(0.5),
      overflowY: "auto",
      [theme.breakpoints.down("md")]: {
        height: "100%",
        width: "100%",
      },
      [theme.breakpoints.between("md", "lg")]: {
        height: "100%",
        width: "70%",
      },
      [theme.breakpoints.up("lg")]: {
        height: "100%",
        width: "70%",
      },
    }));


//Chat container
    interface ChatContainerProps {
      isChatOpen: boolean;
    }
    
    const ChatContainer = styled(Box)<ChatContainerProps>(({ isChatOpen }) => ({
      position: "fixed",
      top: 0,
      left: 0,
      width: "100%",
      height: isChatOpen ? "100vh" : 0,
      display: isChatOpen ? "block" : "none",
      backgroundColor: "white",
      zIndex: 1201,
    }));
    
    ...

//Open/close states
    const [isChatOpen, setIsChatOpen] = useState(false);
    
      const toggleChat = (): void => {
        setIsChatOpen((prevState) => !prevState);
      };
    
    ...
    
    <FirstRoot>
            {children}
            {!isChatOpen && (
              <Box
                sx={{
                  display: { xs: "block", sm: "block", md: "none" }, //Chat is displayed only on mobile
                  zIndex: 1201,
                  position: "fixed",
                  bottom: 25,
                  right: 16,
                  borderRadius: "50%",
                  overflow: "hidden",
                }}
              >
    //Image is the button to open Chat component
                <Image
                  alt="Open Chat"
                  height={80}
                  onClick={toggleChat}
                  src="/kerry_avatar.png"
                  style={{ cursor: "pointer" }}
                  title="Open Chat"
                  width={80}
                />
              </Box>
            )}
    //IF isChatOpen is true it opens the Chat component
            {isChatOpen ? (
              <Box
                sx={{
                  display: { xs: "block", sm: "block", md: "none" },
                }}
              >
                <ChatContainer isChatOpen={isChatOpen}>
                  <Chat onClose={toggleChat} /> //onClose closes the chat Component
                </ChatContainer>
              </Box>
            ) : null}
          </FirstRoot>
next.js components state
1个回答
0
投票

你不应该使用useState,因为当你改变它的值时,它会重新渲染组件,尝试隐藏聊天并使用useRef和js代码显示它

© www.soinside.com 2019 - 2024. All rights reserved.