0

问题是,如果我删除初始值,那么一切正常。我认为具有初始值的数据不会被缓存。但我不知道如何解决这个问题。如果初始数据变异返回未定义。

在页面组件中:

  const { data, error } = useSWR("/api/company/", {
    initialData: company,
  });
export const getServerSideProps: GetServerSideProps<IManage> = async (ctx) => {
  ensureAuth(ctx);
  let company: ICompany[] | null = null;
  await instanceWithSSR(ctx) // axios config
    .get(`/api/company/`)
    .then((response) => {
      company = response?.data;
    })
    .catch((error) => {
      console.log(error);
    });
  return {
    props: {
      company: company || null,
    },
  };
};

我的突变:

  mutate(url, async (company: ICompany[]) => {
    console.log(company)
    if (company) {
      return [...company, companyItem];
    }
  }, false);
4

1 回答 1

2

我不确定您的公司有效负载,但是对于初始值,安装时不会重新验证它,因此您需要将 revalidateOnMount 设置为 true。

 const { data, error, mutate } = useSWR("/api/company/", {
    initialData: company,
    revalidateOnMount: true
  });

useSWR 还提供了一个定位变异,所以你不需要在同一个组件中提供 url。

mutate(async(prev) => [...prev, companyItem])
于 2020-11-22T18:47:15.223 回答