reactjs - 如何在 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 代码塞进钩子吗?
解决方案
getServerSideProps
仅在页面首次加载时调用,因为它会调用 nextjs 的 nodejs 服务器。无论如何,情况总是如此,除非您重新加载/刷新页面。
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
推荐阅读
- java - JavaFX 从 exe 文件中获取图标
- python - 根据给定条件对组合数据进行分组
- css - Tailwind css中带有文本的圆圈
- html - Flexbox - 将元素向右“flex-direction:column”而不使用css中的位置
- php - 在命令模式下运行时出现 PDOException “找不到驱动程序”
- javascript - 如何使用 JSON asp.net MVC 同时发送两个数组以查看
- android - 有没有办法过滤/搜索项目以从 sqlite android 返回列表?
- angular - Angular 10 NgForm
- css - SVG 动画 - 来自中心的 SVG 的 CSS 悬停动画
- node.js - 子域基础数据库连接(nodejs + express)