From 67e106bc20c04576134d2673205df5ed972bd023 Mon Sep 17 00:00:00 2001 From: liuyib <1656081615@qq.com> Date: Tue, 4 Jun 2024 14:38:58 +0800 Subject: [PATCH] refactor: update --- .../hooks/src/useResetState/demo/demo1.tsx | 43 ++++++++++--------- packages/hooks/src/useResetState/index.ts | 8 ++-- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/packages/hooks/src/useResetState/demo/demo1.tsx b/packages/hooks/src/useResetState/demo/demo1.tsx index edfd8e75c1..d77bd29ecf 100644 --- a/packages/hooks/src/useResetState/demo/demo1.tsx +++ b/packages/hooks/src/useResetState/demo/demo1.tsx @@ -1,36 +1,37 @@ -import React, { useRef } from 'react'; +import React, { useMemo } from 'react'; +import { Button, Space } from 'antd'; import { useResetState } from 'ahooks'; -interface State { - hello: string; - value: number; -} - export default () => { - const initialValue = useRef({ + const initialValue = { hello: '', value: Math.random(), - }).current; + }; + const initialValueMemo = useMemo(() => { + return initialValue; + }, []); - const [state, setState, resetState] = useResetState(() => initialValue); + const [state, setState, resetState] = useResetState(initialValue); return (
+
initial state:
+
{JSON.stringify(initialValueMemo, null, 2)}
+
current state:
{JSON.stringify(state, null, 2)}
-
initialValue: {JSON.stringify(initialValue, null, 2)}
-

- - - -

+ + +
); }; diff --git a/packages/hooks/src/useResetState/index.ts b/packages/hooks/src/useResetState/index.ts index 955cb1bd54..eaa7d6000e 100644 --- a/packages/hooks/src/useResetState/index.ts +++ b/packages/hooks/src/useResetState/index.ts @@ -1,7 +1,7 @@ -import { useState } from 'react'; +import { useRef, useState } from 'react'; import type { Dispatch, SetStateAction } from 'react'; -import useMemoizedFn from '../useMemoizedFn'; import { isFunction } from '../utils'; +import useMemoizedFn from '../useMemoizedFn'; import useCreation from '../useCreation'; type ResetState = () => void; @@ -9,8 +9,10 @@ type ResetState = () => void; const useResetState = ( initialState: S | (() => S), ): [S, Dispatch>, ResetState] => { + const initialStateRef = useRef(initialState); const initialStateMemo = useCreation( - () => (isFunction(initialState) ? initialState() : initialState), + () => + isFunction(initialStateRef.current) ? initialStateRef.current() : initialStateRef.current, [], );