无法弄清楚为什么`getStaticProps`在主要导出函数之前没有加载。

huangapple go评论70阅读模式
英文:

Can't figure out why getStaticProps isn't loading before main exported function

问题

我正在使用npm run dev 进行调试,它使用getStaticProps在运行时处理一些d3属性,然后将它们注入主输出函数之前。据我所知,getStaticProps没有运行 - 内部的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 () => {
    // 获取CSV数据并使用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); // 使用output解决Promise
            },
            error: function (error) {
                reject(error); // 如果有错误,拒绝Promise
            }
        });
    });
}

export async function getStaticProps() {
    // 获取数据并创建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, // 在这里返回plots_a
            },
        };
    } catch (err) {
        console.error(err);
        // 在错误情况下,可以返回一个空的props对象或一些默认的props。
        return {
            props: {},
        };
    }
}

const ViolinPlot = ({ width, height, variable, data, xScale }) => {
    // 使用提供的数据和xScale渲染ViolinPlot组件
    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);
        };

        // 初始侧边栏宽度
        handleResize();

        // 窗口调整大小的事件监听器
        window.addEventListener('resize', handleResize);

        // 清理
        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;
英文:

I am using npm run dev to debug this, which uses getStaticProps to process a number of d3 props before injecting it into the main output function at runtime. As far as I can tell, getStaticProps isn't running - a console.log inside it to retrieve keyValues doesn't return anything at all. plots isn't being loaded in the function Sidebar.

import React, { useState, useEffect, useRef } from &quot;react&quot;;
import Papa from &#39;papaparse&#39;;
import { scaleLinear, quantile } from &#39;d3&#39;;
import { ViolinShape } from &quot;components/ViolinShape&quot;;
const fetchData = async () =&gt; {
// Fetch the CSV data and process it using Papa.parse
const response = await fetch(&#39;data_csv/singapore-tess.csv&#39;);
const reader = response.body.getReader();
const result = await reader.read();
const decoder = new TextDecoder(&#39;utf-8&#39;);
const csv = decoder.decode(result.value);
return new Promise((resolve, reject) =&gt; {
Papa.parse(csv, {
header: true,
complete: function (results) {
const output = {};
results.data.forEach(row =&gt; {
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&#39;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 }) =&gt; {
// Render the ViolinPlot component using the provided data and xScale
if (!data || !xScale) {
return &lt;div&gt;Loading...&lt;/div&gt;;
}
return (
&lt;svg style={{ width: width * 0.9, height: height * 2 }}&gt;
&lt;ViolinShape
height={height}
xScale={xScale}
data={data}
binNumber={10}
/&gt;
&lt;/svg&gt;
);
}
const Sidebar = ({ plots, selectedCell, setSelectedCell }) =&gt; {
const [sidebarWidth, setSidebarWidth] = useState(0);
const sidebarRef = useRef(null);
useEffect(() =&gt; {
const handleResize = () =&gt; {
const width = sidebarRef.current.offsetWidth;
setSidebarWidth(width);
};
// Initial sidebar width
handleResize();
// Event listener for window resize
window.addEventListener(&#39;resize&#39;, handleResize);
// Cleanup
return () =&gt; {
window.removeEventListener(&#39;resize&#39;, handleResize);
};
}, []);
return (
&lt;div ref={sidebarRef} className=&quot;sidebar shadow-md bg-zinc-50 overflow-auto&quot;&gt;
{Object.entries(selectedCell).map(([key, value]) =&gt; (
&lt;div key={key} className=&quot;p-4 border mb-4&quot;&gt;
&lt;h3 className=&quot;text-lg font-bold mb-2&quot;&gt;{key}&lt;/h3&gt;
&lt;p&gt;{value}&lt;/p&gt;
{plots[key] &amp;&amp; (
&lt;ViolinPlot
width={sidebarWidth}
height={50}
variable={key}
data={plots[key].data}
xScale={plots[key].xScale}
/&gt;
)}
&lt;/div&gt;
))}
&lt;/div&gt;
);
};
export default Sidebar;

答案1

得分: 0

我从名称中看到这是一个“Sidebar”组件。

getStaticProps函数仅在page文件夹内(即页面)中调用。

如果您想在Sidebar中使用这个数据,那么将getStaticProps函数移到引入Sidebar的页面,并将值作为prop传递给Sidebar组件。

英文:

I am see from the name that this is a Sidebar component.

getStaticProps function is only invoked inside the page folder (i.e Pages).

If you want to use this data in Sidebar, then move the getStaticProps function to a page where the Sidebar is imported and the pass the value to the Sidebar component as prop.

huangapple
  • 本文由 发表于 2023年6月22日 11:29:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定