最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - React.js does not hydrate the root element but rather renders it twice - Stack Overflow

programmeradmin1浏览0评论

I have developed pre-rendering (similar to react-snap) in my React 18 application (which means I have index.html generated during the build process and React hydrates it). I use the following code in my main React index.ts (as it was recommended in react-snap docs):

const rootElement = document.getElementById("root")!;
const isSsr = rootElement.hasChildNodes();

const reactNode = (
    <StyledEngineProvider injectFirst>
        <ThemeProvider theme={AppTheme}>
            <CssBaseline />
            <AppContext.Provider value={appState}>
                <SnackbarProvider
                    maxSnack={5}
                    anchorOrigin={{
                        vertical: "bottom",
                        horizontal: "right",
                    }}
                    ref={notistackRef}
                    action={(key) => (
                        <IconButton style={{ color: "white" }} onClick={onClickDismiss(key)}>
                            <CloseIcon />
                        </IconButton>
                    )}
                >
                    <HelmetProvider>
                        <BrowserRouter>
                            <AppLayout />
                        </BrowserRouter>
                    </HelmetProvider>
                </SnackbarProvider>
            </AppContext.Provider>
        </ThemeProvider>
    </StyledEngineProvider>
);

if (isSsr) {
    hydrateRoot(rootElement, reactNode, { onRecoverableError: console.log });
} else {
    createRoot(rootElement).render(reactNode);
}

This code seems to be working good for the most of the pages and I get the following correct markup in HTML (one html child node insite #root):

<div id="root">
    <div style="width: 100%">...</div>
</div>

however for some pages I see the following anomaly:

<div id="root">
    <div style="width: 100%">...</div>
    <div style="width: 100%">...</div>
</div>

So #root now contains two children instead of just one. I have no any hydration errors reported in the console.

Any ideas why this may happen?

Normal (if no pre-rendering) React rendering works good for those pages. HTML generated by the prerenderer also looks good.

发布评论

评论列表(0)

  1. 暂无评论