为什么prevvalue不使用javascript更新并做出反应?

问题描述

我想设置日历的开始和结束日期。

最初的开始日期和结束日期未预定义。 当用户仅单击开始日期时,结束日期也将设置为开始日期,并且focusedinput变为结束日期。当用户单击结束时,将突出显示从开始到结束的所选日期范围。

现在,当用户单击设置为开始日期的另一个日期时,现在将结束日期设置为开始日期。当用户单击结束时,将突出显示从开始到结束的所选日期范围。

又是相同的过程。

下面是我的代码

const useRangeDates = () => {
    const [startDate,setStartDate] = React.useState<Moment | null>(null);
    const [endDate,setEndDate] = React.useState<Moment | null>(null);
    const [focusedInput,setFocusedInput] = React.useState('startDate');

    const usePrevIoUs = (value: any) => {
        const ref = React.useRef();

        React.useEffect(() => {
            ref.current = value;
        },[value]);

        return ref.current;
    };

    const prevDate = usePrevIoUs(startDate);

    const updateStartDate = (newStartDate: any) => {
        setFocusedInput('endDate');
        setStartDate(newStartDate);
    };

    const updateStartEnd = (newEndDate: any,newStartDate: any) => {
        if (prevDate && newStartDate && newStartDate.isBefore(prevDate,'d')) {//here i am checking if the newstartdate is before prevstartdate
            setEndDate(newStartDate);
        } else {
            setEndDate(newEndDate);
        }
    };

    const onDatesChange = (newDates: {startDate,endDate})
    }) => {
        updateStartDate(newDates.startDate);
        if (newDates.endDate !== null) {
            updateStartEnd(newDates.endDate,newDates.startDate);
        } else {
            updateStartEnd(newDates.startDate,newDates.startDate);
        }
    };

    return {
        focusedInput,onDatesChange,isOutsideRange,startDate,endDate,onFocusChange: (focused: string) => {
            setFocusedInput(!focused ? 'startDate' : focused);
        },};
};

function CreationForm() {
    const {
        focusedInput,onFocusChange,} = useRangeDates();


    return (
        <DayPickerRangeController
            startDate={startDate}
            endDate={endDate}
            focusedInput={focusedInput}
            onFocusChange={onFocusChange}
        />
    );
}

代码可以正常工作。但是当我选择上一个开始日期之前的日期时,则将结束日期设置为结束日期。当用户单击结束日期时,这将进入updatestartend中的条件,然后将enddate设置为startdate。这是因为prevdate与以前的prevdate相同,因此未更新。

我希望当用户要单击结束日期时,它现在是newstartdate。

我不确定出了什么问题。有人可以帮我吗谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)