首页 > 解决方案 > 如何在 Next.js 中使用 useEffect 调用 getServerSideprops

问题描述

我正在使用 next.js 构建一个项目,但我有一个问题,即在呈现页面时 getServerSideProps 被调用了 6 次。

这是页面顶部的代码。

const NewFindstay: React.FC<INewFindstayProps> = ({ findstayList }) => {
  const [isMap, setIsMap] = useState(false);
  return (
    <div id="contents">
      <FindstayFilter setIsMap={setIsMap} isMap={isMap} />
      <FindstayList findstayList={findstayList} isMap={isMap} />
    </div>
  );
};

export async function getServerSideProps({ query, req }) {
  let findstayList = null;
  try {
    findstayList = await getPlaceListAsync(
      { ...query },
      req.headers.cookie ? req.headers.cookie : null
    );
  } catch (e) {
    findstayList = null;
  }
  return {
    props: {
      findstayList,
      query,
    },
  };
}

export default NewFindstay;

似乎这是由在 FindstayFilter 中导入的组件引起的。(假设组件 A、B、C、D、E、F)

A、B、C、D、E、F 的每个组件都有 setState 的 useEffect 钩子。

// A
 useEffect(() => {
    if (router.query.city) {
      setSelectedCity(router.query.city);
    };
  }, [router.query.city]);

// B
  useEffect(() => {
    setDateRange({
      startDate: check_in ? moment(check_in) : null,
      endDate: check_out ? moment(check_out) : null
    })
  }, [router.query.check_in, router.query.check_out]);
// C
  useEffect(() => {
    const queryPrice = {
      min: price_min ? (parseInt(price_min as string, 10) / 10000) : 0,
      max: price_max ? (parseInt(price_max as string, 10) / 10000) : 100
    }
    setRangePrice(queryPrice);
  }, [router.query.price_min, router.query.price_max]);

// D, E, F use same pattern as well.

也就是说,FindstayFilter 组件渲染时,A、B、C、D、E、F 内部的 useEffect hook 总共重新渲染组件 6 次,触发调用 getServerSideProps 也是 6 次。

如何最小化调用 getServerSideProps?我应该只在 FindstayFilter 组件内部使用 useEffect 钩子并将许多 setstate 代码塞进钩子吗?

标签: reactjsreact-hooksnext.js

解决方案


getServerSideProps仅在页面首次加载时调用,因为它会调用 nextjs 的 nodejs 服务器。无论如何,情况总是如此,除非您重新加载/刷新页面。 https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering


推荐阅读