docs: fix hydration error when resizing (#41370)

* docs: fix hydration error when resizing

* docs: useLayoutState
This commit is contained in:
MadCcc 2023-03-21 13:00:16 +08:00 committed by GitHub
parent bb8b52936c
commit 772ab49baf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 9 deletions

View File

@ -0,0 +1,17 @@
import { startTransition, useState } from 'react';
const useLayoutState = <S>(
...args: Parameters<typeof useState<S>>
): ReturnType<typeof useState<S>> => {
const [state, setState] = useState<S>(...args);
const setLayoutState: typeof setState = (...setStateArgs) => {
startTransition(() => {
setState(...setStateArgs);
});
};
return [state, setLayoutState];
};
export default useLayoutState;

View File

@ -5,15 +5,16 @@ import {
parentSelectorLinter,
StyleProvider,
} from '@ant-design/cssinjs';
import { ConfigProvider, theme as antdTheme, App } from 'antd';
import { App, ConfigProvider, theme as antdTheme } from 'antd';
import type { DirectionType } from 'antd/es/config-provider';
import { createSearchParams, useOutlet, useSearchParams } from 'dumi';
import React, { startTransition, useCallback, useEffect, useMemo } from 'react';
import React, { useCallback, useEffect, useMemo } from 'react';
import useLocation from '../../hooks/useLocation';
import type { ThemeName } from '../common/ThemeSwitch';
import ThemeSwitch from '../common/ThemeSwitch';
import type { SiteContextProps } from '../slots/SiteContext';
import SiteContext from '../slots/SiteContext';
import useLayoutState from '../../hooks/useLayoutState';
type Entries<T> = { [K in keyof T]: [K, T[K]] }[keyof T][];
type SiteState = Partial<Omit<SiteContextProps, 'updateSiteContext'>>;
@ -40,7 +41,7 @@ const GlobalLayout: React.FC = () => {
const outlet = useOutlet();
const { pathname } = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
const [{ theme, direction, isMobile }, setSiteState] = React.useState<SiteState>({
const [{ theme, direction, isMobile }, setSiteState] = useLayoutState<SiteState>({
isMobile: false,
direction: 'ltr',
theme: ['light'],
@ -85,11 +86,9 @@ const GlobalLayout: React.FC = () => {
const _theme = searchParams.getAll('theme') as ThemeName[];
const _direction = searchParams.get('direction') as DirectionType;
startTransition(() => {
setSiteState({ theme: _theme, direction: _direction === 'rtl' ? 'rtl' : 'ltr' });
// Handle isMobile
updateMobileMode();
});
setSiteState({ theme: _theme, direction: _direction === 'rtl' ? 'rtl' : 'ltr' });
// Handle isMobile
updateMobileMode();
window.addEventListener('resize', updateMobileMode);
return () => {

View File

@ -203,7 +203,7 @@
"cheerio": "1.0.0-rc.12",
"cross-env": "^7.0.0",
"dekko": "^0.2.1",
"dumi": "^2.1.13",
"dumi": "^2.1.17",
"duplicate-package-checker-webpack-plugin": "^3.0.0",
"esbuild-loader": "^3.0.0",
"eslint": "^8.0.0",