reactjs 无法使用react day picker和Next.js设置初始日期

0aydgbwb  于 12个月前  发布在  React
关注(0)|答案(1)|浏览(140)

我正在使用Next.js,React Query和React Day Picker与React Hook Form。
我正在使用React Query从一个端点获取一些日期,我想将这些日期设置为选择的初始日期。如果我浏览网站并转到页面,则日期显示为选定的日期。但是,如果我刷新页面,则不会显示日期。我必须导航到另一个页面并返回以查看选定的日期。

const {
    data: initialDatesTest,
    error,
    isLoading,
  } = useQuery({
    queryKey: ["dates"],
    queryFn: getDates,
  });
  async function getDates() {
    const response = await fetch("/api/dates-to-exclude");
    const data = await response.json();
    const parsedExcludedDates = data.excludedDates.PartyExcludeDates.map(
      (dateString: string) => new Date(dateString)
    );

    return parsedExcludedDates;
  }

const initialDays: Date[] = initialDatesTest || [];
const [days, setDays] = useState<Date[] | undefined>(initialDays);

      <Controller
        control={control}
        name="DayPicker"
        render={({ field }) => (
          <DayPicker
            mode="multiple"
            min={1}
            selected={days}
            onSelect={setDays}
            footer={footer}
            disabled={{ before: new Date() }}
            numberOfMonths={1}
          />
        )}
      />

字符串

krugob8w

krugob8w1#

这是因为initialDatesTest在获取数据之前是未定义的,并且初始值仅在第一次渲染时设置。您希望在useQueryonSuccess中调用setDays。类似于

const {
  data: initialDatesTest,
  error,
    isLoading,
} = useQuery({
  queryKey: ["dates"],
  queryFn: getDates,
});

async function getDates() {
  const response = await fetch("/api/dates-to-exclude");
  const data = await response.json();
  const parsedExcludedDates = data.excludedDates.PartyExcludeDates.map(
    (dateString: string) => new Date(dateString)
  );

  setDates(parsedExcludedDates); // update state to reflect what was returned from server.

  return parsedExcludedDates;
}

字符串

相关问题