【问题标题】:Next.js: Prop drilling a ton of data recieved from getStaticProps or using Context API?Next.js:从 getStaticProps 或使用 Context API 接收大量数据的道具?
【发布时间】:2022-06-17 01:20:32
【问题描述】:

我正在为我的学校项目使用带有增量静态再生的 Next.js 构建一个带有迷你论坛的应用程序,但在道具钻孔方面遇到了一些麻烦。我有这个道具流程 getStaticProps => backgroundLayout => mainPage => 其他页面组件

我正在考虑使用上下文 API 来解决问题,但我担心上下文 API 会变得不堪重负,并且可能会随着论坛的发展而减慢应用程序的速度。我已经学会将上下文 API 仅用于全局上下文,而论坛只是应用程序的一小部分。但是,我需要更多次使用 SSR 和 ISR 使用大量数据来实现道具钻探(如下面的代码),因此上下文 API 可能会成为瓶颈。一个人应该选择做什么?继续使用道具钻孔还是使用 Context API?

import React from "react";
import styles from "./index.module.css";
import Layout from "../../components/_layout";
import { GetStaticProps } from "next";
import dbExecute from "../../_operations/db/db";
import OuterForumLeft from "../../components/school-forum/left";
import OuterForumRight from "../../components/school-forum/right";
interface Props {
    data: {
        question_id: number;
        question_header: string;
        question_body: string;
        question_timestamp: string;
        account_first_name: string;
        account_last_name: string;
        section_grade: string;
        section_strand: string;
    };
}
export const SchoolForum: React.FC<Props> = ({ data }) => {
    return (
        <>
            <section className={styles.outermostForumSection}>
                // passes again
                <OuterForumLeft />
                <OuterForumRight />
            </section>
        </>
    );
};

const SchoolForumPage: React.FC<Props> = ({ data }) => {
    return (
        <>
            <Layout page={<SchoolForum data={data} />} />
        </>
    );
};
export default SchoolForumPage;

export const getStaticProps: GetStaticProps = async () => {

    const sql: string = `SELECT * FROM account_table`;
    const [sqlData] = await dbExecute(sql);
    return {
        props: {
            data: sqlData,
        },
    };
};

【问题讨论】:

    标签: next.js react-props react-context forum


    【解决方案1】:

    您可以使用上下文 api + swr 作为全局状态管理。我这里详细解释了:

    Global state management and Next.js

    SWR 得名于 stale-while-revalidate ,一种缓存策略 这在前端领域越来越受欢迎。它允许我们加载 立即缓存内容,同时刷新 内容,以便将来提供更新的内容。

    【讨论】:

      【解决方案2】:

      我们现在有一个可用的库,即

      next-common-props 将允许您访问任何页面嵌套组件内的数据。你只需要声明一个配置文件。

      工作示例是here

      使用相同的库,您不必对大量数据进行任何道具钻探。

      【讨论】:

        猜你喜欢
        • 2023-01-22
        • 2021-06-11
        • 2021-06-07
        • 2023-03-19
        • 1970-01-01
        • 2021-05-12
        • 2019-03-04
        • 1970-01-01
        相关资源
        最近更新 更多