next.js 无法弄清楚为什么getStaticProps没有在主导出函数之前加载

n3schb8v  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(103)

我使用npm run dev来调试它,它使用getStaticProps来处理一些d3 props,然后在运行时将其注入主输出函数。据我所知,getStaticProps并没有运行--其中用于检索keyValues的console.log根本没有返回任何东西。函数Sidebar中未加载plots。

import React, { useState, useEffect, useRef } from "react";
import Papa from 'papaparse';
import { scaleLinear, quantile } from 'd3';
import { ViolinShape } from "components/ViolinShape";

const fetchData = async () => {
    // Fetch the CSV data and process it using Papa.parse
    const response = await fetch('data_csv/singapore-tess.csv');
    const reader = response.body.getReader();
    const result = await reader.read();
    const decoder = new TextDecoder('utf-8');
    const csv = decoder.decode(result.value);

    return new Promise((resolve, reject) => {
        Papa.parse(csv, {
            header: true,
            complete: function (results) {
                const output = {};
                results.data.forEach(row => {
                    for (const key in row) {
                        if (!output[key]) output[key] = [];
                        output[key].push(row[key]);
                    }
                });
                resolve(output); // resolve the Promise with the output
            },
            error: function (error) {
                reject(error); // reject the Promise if there's an error
            }
        });
    });
}

export async function getStaticProps() {
    // Fetch the data and create a dictionary of plots
    try {
        const keyValues = await fetchData();

        const plots_a = {};

        for (const key in keyValues) {
            const data = keyValues[key];
            const p5 = quantile(data.sort(), 0.05);
            const p95 = quantile(data, 0.95);
            const xS = scaleLinear().domain([p5, p95]).range([0, width]);

            plots_a[key] = {
                data,
                xScale: xS,
            };
        }

        console.log(plots_a);

        return {
            props: {
                plots: plots_a, // return plots_a here
            },
        };
    } catch (err) {
        console.error(err);
        // You can return an empty props object or some default props in case of an error.
        return {
            props: {},
        };
    }
}

const ViolinPlot = ({ width, height, variable, data, xScale }) => {
    // Render the ViolinPlot component using the provided data and xScale
    if (!data || !xScale) {
        return <div>Loading...</div>;
    }

    return (
        <svg style={{ width: width * 0.9, height: height * 2 }}>
            <ViolinShape
                height={height}
                xScale={xScale}
                data={data}
                binNumber={10}
            />
        </svg>
    );
}

const Sidebar = ({ plots, selectedCell, setSelectedCell }) => {

    const [sidebarWidth, setSidebarWidth] = useState(0);
    const sidebarRef = useRef(null);

    useEffect(() => {
        const handleResize = () => {
            const width = sidebarRef.current.offsetWidth;
            setSidebarWidth(width);
        };

        // Initial sidebar width
        handleResize();

        // Event listener for window resize
        window.addEventListener('resize', handleResize);

        // Cleanup
        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    return (
        <div ref={sidebarRef} className="sidebar shadow-md bg-zinc-50 overflow-auto">
            {Object.entries(selectedCell).map(([key, value]) => (
                <div key={key} className="p-4 border mb-4">
                    <h3 className="text-lg font-bold mb-2">{key}</h3>
                    <p>{value}</p>
                    {plots[key] && (
                        <ViolinPlot
                            width={sidebarWidth}
                            height={50}
                            variable={key}
                            data={plots[key].data}
                            xScale={plots[key].xScale}
                        />
                    )}
                </div>
            ))}
        </div>
    );
};

export default Sidebar;
vkc1a9a2

vkc1a9a21#

我从名字中看出这是一个Sidebar组件。
getStaticProps函数仅在page文件夹(即Pages)中调用。
如果您想在Sidebar中使用此数据,请将getStaticProps函数移动到导入Sidebar的页面,并将值作为prop传递给Sidebar组件。

相关问题