0

每当我在 swr 中请求具有不同查询参数的新数据时(即单击上一个和下一个按钮),都会在我的代码中触发加载。这意味着数据似乎已被清除,然后被新数据替换。我怎样才能使旧数据被新数据替换,从而不触发加载?

组件.ts

import React, { useState } from "react";
import { cloneDeep } from "lodash";

import Day from "components/Day";
import DragDropContext from "shared/components/DragDropContext";
import Loading from "shared/components/Loading";
import task from "services/taskService";
import { DragEndResult, ITaskList } from "types";
import { addDays } from "utils/dateTime";

import styles from "./Days.module.scss";

const Days = () => {
  const firstDay = addDays(new Date(), -1);
  const [dates, setDates] = useState({
    start: firstDay,
    end: addDays(firstDay, 4)
  })

  const { data: taskLists, mutate } = task.current(dates.start, dates.end);

  const handleArrowClick = async (direction: "prev" | "next") => {
    if(direction === "next") {
     setDates({
       start: addDays(dates.start, 1),
       end: addDays(dates.end, 1),
     });
    } else if (direction === "prev") {
      setDates({
       start: addDays(dates.start, -1),
       end: addDays(dates.end, -1),
     });
    }
  }

  return (
    <>
      {!taskLists && <Loading />}
      <div className={styles.days}>
        <div className={styles.prev} onClick={() => handleArrowClick("prev")}>
          <div className={styles.arrow}></div>
        </div>
        <div className={styles["days__slide"]}>
          <DragDropContext onDragEnd={handleDragEnd}>
            {taskLists &&
              Object.values(taskLists).map((taskList: ITaskList) => {
                return (
                  <Day
                    key={taskList.date}
                    onAddTask={handleAddTask}
                    onRemove={handleRemoveTask}
                    {...taskList}
                  />
                );
              })}
          </DragDropContext>
        </div>
        <div className={styles.next} onClick={() => handleArrowClick("next")}>
          <div className={styles.arrow}></div>
        </div>
      </div>
    </>
  );
};

export default Days;


任务服务.ts

const current = (start: Date, end: Date) =>
  useSWR(
    ["/tasks", formatDateForApi(start), formatDateForApi(end)],
    async (url, startQuery, endQuery) => {
      const finalUrl = `${url}?start=${startQuery}&end=${endQuery}`;
      const res = await httpService.get(finalUrl);
      return res.data;
    },
    { refreshInterval: 1000 }
  );
4

0 回答 0