如何为当前的 useState 用法创建自定义挂钩

how to create a custom hook on react for this current useState usage

我目前正在学习反应和自定义挂钩,我得到了这个,但不确定在这种情况下应该如何拥有自定义挂钩,return 应该是什么,我必须 return?,如有任何帮助,我们将不胜感激,在此先感谢您

const [newResultDate, setNewResultDate] = useState<Date>(
            (() => {
                if (value?.startDate) {
                    return new Date(value.startDate);
                } else if (value?.daysUpToDay) {
                    return new Date();
                }
                try {
                    const date = new Date(value);
                    if (date && date.toString() !== 'Invalid Date') {
                        return date;
                    }
                } catch (e) {
                    // noop
                }
                return new Date();
            })()
        );

可能的自定义挂钩:

const useCustomHook = (dateFilter: ( dateProps)) => {
    const [newResultDate, setNewResultDate] = useState<Date>();

    const setDateValue = (val) => setNewResultDate(val);

    if (dateFilter?.startDate) {
        setNewResultDate(new Date(dateFilter.startDate));
    } else if (dateFilter?.daysUpToDay) {
        setNewResultDate(new Date());
    }
    try {
        const date = new Date(dateFilter as any);
        if (date && date.toString() !== 'Invalid Date') {
            setNewResultDate(date);
        }
    } catch (e) {
        // noop
    }
    setNewResultDate(new Date());

    return [newResultDate, setDateValue] as const;
};


is this correct?

how is supposed to be used on my component?

我相当确定你不能从传递给有效“构造函数”的惰性初始化函数中调用状态更新器.

与其尝试“设置状态”,不如 return 您希望初始状态的值。将 value 传递给 您的 挂钩,以便它可以传递给初始化函数。

const initializeState = (value) => {
  if (value?.startDate) {
    return new Date(value.startDate);
  } else if (value?.daysUpToDay) {
    return new Date();
  }
  try {
    const date = new Date(value);
    if (date?.toString() !== 'Invalid Date') {
      return date;
    }
  } catch (e) {
    // noop
  }
  return new Date();
});

const useCustomHook(value) => {
  const [newResultDate, setNewResultDate] = useState<Date>(() => initializeState(value));
  return [newResultDate, setNewResultDate] ;
}

用法:

useCustomHook({ startDate: "2022-01-22" });