Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: optimized usage of useState initializer function #3263

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion site/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function Components() {
const tdDocSearch = useRef();

const [version] = useState(currentVersion);
const [globalConfig] = useState(getLang() === 'en' ? enConfig : zhConfig);
const [globalConfig] = useState(() => getLang() === 'en' ? enConfig : zhConfig);

function initHistoryVersions() {
fetch(registryUrl)
Expand Down
6 changes: 3 additions & 3 deletions src/calendar/Calendar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,9 @@ const Calendar = forwardRef<CalendarMethods, CalendarProps>((props, ref) => {
const { visible: visibleForCurrent = true, currentDayButtonProps = {}, currentMonthButtonProps = {} } = current;

const [mode, setMode] = useState<string>('month');
const [value, setValue] = useState<dayjs.Dayjs>(dayjs(valueFromProps || dayjs().format('YYYY-MM-DD')));
const [year, setYear] = useState<number>(yearProps ? Number(yearProps) : value.year());
const [month, setMonth] = useState<number>(monthProps ? Number(monthProps) : parseInt(value.format('M'), 10));
const [value, setValue] = useState<dayjs.Dayjs>(() => dayjs(valueFromProps || dayjs().format('YYYY-MM-DD')));
const [year, setYear] = useState<number>(() => (yearProps ? Number(yearProps) : value.year()));
const [month, setMonth] = useState<number>(() => (monthProps ? Number(monthProps) : parseInt(value.format('M'), 10)));
const [isShowWeekend, setIsShowWeekend] = useState<boolean>(isShowWeekendDefault);

const [local, t] = useLocaleReceiver('calendar');
Expand Down
2 changes: 1 addition & 1 deletion src/color-picker/components/panel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const Panel = forwardRef<HTMLDivElement, ColorPickerProps>((props, ref) => {
onRecentColorsChange,
} = props;
const [innerValue, setInnerValue] = useControlled(props, 'value', onChange);
const [mode, setMode] = useState<TdColorModes>(colorModes?.length === 1 ? colorModes[0] : 'monochrome');
const [mode, setMode] = useState<TdColorModes>(() => (colorModes?.length === 1 ? colorModes[0] : 'monochrome'));
const [updateId, setUpdateId] = useState(0);

const isGradient = mode === 'linear-gradient'; // 判断是否为 linear-gradient 模式
Expand Down
2 changes: 1 addition & 1 deletion src/date-picker/base/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const DatePickerHeader = (props: DatePickerHeaderProps) => {
},
[mode],
);
const [yearOptions, setYearOptions] = useState(initOptions(year));
const [yearOptions, setYearOptions] = useState(() => initOptions(year));

// 年份选择展示区间
const nearestYear: number = useMemo(
Expand Down
2 changes: 1 addition & 1 deletion src/date-picker/hooks/useRange.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default function useRange(props: TdDateRangePickerProps) {
const [isHoverCell, setIsHoverCell] = useState(false);
const [activeIndex, setActiveIndex] = useState(0); // 确定当前选中的输入框序号
// 未真正选中前可能不断变更输入框的内容
const [inputValue, setInputValue] = useState(formatDate(value, { format }));
const [inputValue, setInputValue] = useState(() => formatDate(value, { format }));

// input 设置
const rangeInputProps = {
Expand Down
8 changes: 4 additions & 4 deletions src/date-picker/hooks/useRangeValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,13 @@ export default function useRange(props: TdDateRangePickerProps) {

const [isFirstValueSelected, setIsFirstValueSelected] = useState(false); // 记录面板点击次数,两次后才自动关闭
const [time, setTime] = useState(
initYearMonthTime({ value, mode: props.mode, format, enableTimePicker: props.enableTimePicker }).time,
() => initYearMonthTime({ value, mode: props.mode, format, enableTimePicker: props.enableTimePicker }).time,
);
const [month, setMonth] = useState<Array<number>>(
initYearMonthTime({ value, mode: props.mode, format, enableTimePicker: props.enableTimePicker }).month,
() => initYearMonthTime({ value, mode: props.mode, format, enableTimePicker: props.enableTimePicker }).month,
);
const [year, setYear] = useState<Array<number>>(initYearMonthTime({ value, mode: props.mode, format }).year);
const [cacheValue, setCacheValue] = useState(formatDate(value, { format })); // 缓存选中值,panel 点击时更改
const [year, setYear] = useState<Array<number>>(() => initYearMonthTime({ value, mode: props.mode, format }).year);
const [cacheValue, setCacheValue] = useState(() => formatDate(value, { format })); // 缓存选中值,panel 点击时更改

// 输入框响应 value 变化
useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/date-picker/hooks/useSingle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default function useSingleInput(props: TdDatePickerProps) {
const [popupVisible, setPopupVisible] = useState(false);
const [isHoverCell, setIsHoverCell] = useState(false);
// 未真正选中前可能不断变更输入框的内容
const [inputValue, setInputValue] = useState(formatDate(value, { format }));
const [inputValue, setInputValue] = useState(() => formatDate(value, { format }));

// input 设置
let inputProps: TdDatePickerProps['inputProps'] & { ref?: React.MutableRefObject<HTMLInputElement> } = {
Expand Down
2 changes: 1 addition & 1 deletion src/form/FormItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const FormItem = forwardRef<FormItemInstance, FormItemProps>((originalProps, ref
const [verifyStatus, setVerifyStatus] = useState('validating');
const [resetValidating, setResetValidating] = useState(false);
const [needResetField, setNeedResetField] = useState(false);
const [formValue, setFormValue] = useState(
const [formValue, setFormValue] = useState(() =>
getDefaultInitialData({
children,
initialData,
Expand Down
2 changes: 1 addition & 1 deletion src/grid/Row.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const Row = forwardRef<HTMLElement, RowProps>((props, ref) => {
...otherRowProps
} = useDefaultProps<RowProps>(props, rowDefaultProps);

const [size, setSize] = useState(canUseDocument ? calcSize(window.innerWidth) : 'md');
const [size, setSize] = useState(() => (canUseDocument ? calcSize(window.innerWidth) : 'md'));

const updateSize = () => {
const currentSize = calcSize(window.innerWidth);
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useVirtualScroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ const useVirtualScroll = (container: MutableRefObject<HTMLElement>, params: UseV
/** 注意测试:数据长度为空;数据长度小于表格高度等情况。即期望只有数据量达到一定程度才允许开启虚拟滚动 */
const [visibleData, setVisibleData] = useState<any[]>([]);
// 滚动过程中表格顶部占位距离
const [translateY, setTranslateY] = useState((data?.length || 0) * (scroll?.rowHeight || 50));
const [translateY, setTranslateY] = useState(() => (data?.length || 0) * (scroll?.rowHeight || 50));
// 滚动高度,用于显示滚动条
const [scrollHeight, setScrollHeight] = useState(0);
const trScrollTopHeightList = useRef<number[]>([]);
// 已经通过节点渲染计算出来的各自行高
const [trHeightList, setTrHeightList] = useState<number[]>([]);
const containerWidth = useRef(0);
const containerHeight = useRef(0);
const [startAndEndIndex, setStartAndEndIndex] = useState<[number, number]>([0, (scroll?.bufferSize || 10) * 3]);
const [startAndEndIndex, setStartAndEndIndex] = useState<[number, number]>(() => [0, (scroll?.bufferSize || 10) * 3]);

// 设置初始值
const tScroll = useMemo(() => {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useWindowSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function useWindowSize(): WindowSize {
[validWindow],
);

const [size, setSize] = useState(getSize());
const [size, setSize] = useState(getSize);

useEffect(() => {
function handleResize() {
Expand Down
2 changes: 1 addition & 1 deletion src/loading/Loading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const Loading: React.FC<LoadingProps> = (props) => {
style,
} = useDefaultProps<LoadingProps>(props, loadingDefaultProps);

const [showLoading, setShowLoading] = useState(delay ? false : loading);
const [showLoading, setShowLoading] = useState(() => (delay ? false : loading));

const { classPrefix } = useConfig();

Expand Down
2 changes: 1 addition & 1 deletion src/swiper/Swiper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const Swiper: React.FC<SwiperProps> & Record<'SwiperItem', typeof SwiperItem> =

const [currentIndex, setCurrentIndex] = useState(defaultCurrent);
const [needAnimation, setNeedAnimation] = useState(false);
const [arrowShow, setArrowShow] = useState(navigationConfig.showSlideBtn === 'always');
const [arrowShow, setArrowShow] = useState(() => navigationConfig.showSlideBtn === 'always');
const swiperTimer = useRef<ReturnType<typeof setTimeout>>(null); // 计时器指针
const swiperAnimationTimer = useRef<ReturnType<typeof setTimeout>>(null); // 计时器指针
const isHovering = useRef<boolean>(false);
Expand Down
2 changes: 1 addition & 1 deletion src/table/EditableCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const EditableCell = (props: EditableCellProps) => {
const { Edit1Icon } = useGlobalIcon({ Edit1Icon: TdEdit1Icon });
const tableEditableCellRef = useRef(null);
const isKeepEditMode = Boolean(col.edit?.keepEditMode);
const [isEdit, setIsEdit] = useState(isKeepEditMode || props.col.edit?.defaultEditable || false);
const [isEdit, setIsEdit] = useState(() => isKeepEditMode || props.col.edit?.defaultEditable || false);
const [editValue, setEditValue] = useState();
const [errorList, setErrorList] = useState<AllValidateResult[]>([]);
const { classPrefix } = useConfig();
Expand Down
2 changes: 1 addition & 1 deletion src/table/hooks/useFixed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ export default function useFixed(
// CSS 样式设置了固定 6px
const [scrollbarWidth, setScrollbarWidth] = useState(6);
// 固定列、固定表头、固定表尾等内容的位置信息
const [rowAndColFixedPosition, setRowAndColFixedPosition] = useState<RowAndColFixedPosition>(new Map());
const [rowAndColFixedPosition, setRowAndColFixedPosition] = useState<RowAndColFixedPosition>(() => new Map());
const [showColumnShadow, setShowColumnShadow] = useState({
left: false,
right: false,
Expand Down
2 changes: 1 addition & 1 deletion src/table/hooks/useLazyLoad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function useLazyLoad(
) {
// useMemo 用意:1. 为了实时响应数据;2. 表格的计算量容易过大,提前存储
const tRowHeight = useMemo(() => Math.max(params.rowHeight || 48, 48), [params.rowHeight]);
const [isInit, setIsInit] = useState(params.rowIndex === -1);
const [isInit, setIsInit] = useState(() => params.rowIndex === -1);
const hasLazyLoadHolder = useMemo(() => params?.type === 'lazy' && !isInit, [isInit, params?.type]);

const requestAnimationFrame =
Expand Down
2 changes: 1 addition & 1 deletion src/table/hooks/useRowspanAndColspan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default function useRowspanAndColspan(
rowKey: string,
rowspanAndColspan: TableRowspanAndColspanFunc<TableRowData>,
) {
const [skipSpansMap, setKipSnapsMap] = useState(new Map<string, SkipSpansValue>());
const [skipSpansMap, setKipSnapsMap] = useState(() => new Map<string, SkipSpansValue>());

// 计算单元格是否跳过渲染
const onTrRowspanOrColspan = (
Expand Down
2 changes: 1 addition & 1 deletion src/table/hooks/useTreeData.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface UseSwapParams<T> extends SwapParams<T> {

export default function useTreeData(props: TdEnhancedTableProps) {
const { data, columns, tree, rowKey, treeExpandAndFoldIcon, expandedTreeNodes } = props;
const [store] = useState(new TableTreeStore() as InstanceType<typeof TableTreeStore>);
const [store] = useState(() => new TableTreeStore() as InstanceType<typeof TableTreeStore>);
const [treeNodeCol, setTreeNodeCol] = useState<PrimaryTableCol>(() => getTreeNodeColumnCol());
const [dataSource, setDataSource] = useState<TdEnhancedTableProps['data']>(data || []);
const { tableTreeClasses } = useClassName();
Expand Down
2 changes: 1 addition & 1 deletion src/tabs/Tabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const Tabs = forwardRefWithStatics(
});

// 当未设置默认值时,默认选中第一个。
const [value, setValue] = React.useState<TabValue>(
const [value, setValue] = React.useState<TabValue>(() =>
defaultValue === undefined && Array.isArray(itemList) && itemList.length !== 0 ? itemList[0].value : defaultValue,
);

Expand Down
Loading