英文:
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 "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;
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论