1 回答

TA貢獻1876條經驗 獲得超5個贊
經過更多的挖掘后,我發現了這個問題,在這里發布希望可以幫助未來的讀者解決同樣的問題。
罪魁禍首是這樣的:
const dynamicPath = `../../posts/${slug}.json`; // for eslint parsing error: "Cannot read property 'range' of null Occurred while linting"
const content = await import(dynamicPath);
在動態導入中使用變量不起作用,只能使用字符串或模板文字。我使用了一個變量,因為 eslint 解析錯誤,只能通過降級到早期版本的 eslint 來解決。這會導致 eslint 在這個文件中無法為我工作,但是沒關系,至少該函數被調用了。
這與在調用之前調用組件代碼的觀察相結合,getStaticProps使得 jsonFile 變量未定義,并且整個組件在到達getStaticProps. 您可以看到以 開頭的日志121212早于1212。終端日志:
121212 {
fileRelativePath: 'posts/hello.json',
data: { title: 'Not the actual data' }
}
1212 hello
這對我來說是違反直覺的,因為我認為它會首先獲取道具并立即將它們傳遞給組件,但遺憾的是,需要定義默認道具來解決這個問題。
新代碼:
import React from 'react';
import glob from 'glob';
import { usePlugin } from 'tinacms';
import { useJsonForm } from 'next-tinacms-json';
const Page = ({ jsonFile }) => {
console.log(121212, jsonFile);
// Get content and form for Tina
const [content, form] = useJsonForm(jsonFile);
// Register it with the CMS
usePlugin(form);
return (
<h1>
{content.title}
</h1>
);
};
Page.defaultProps = {
jsonFile: {
fileRelativePath: 'posts/hello.json',
data: {
title: 'Not the actual data',
},
},
};
export default Page;
/**
* By exporting the async function called getStaticProps from a page, Next.js
* pre-renders this page at build time using the props returned by
* getStaticProps.
*/
export async function getStaticProps({ params: { slug } }) {
console.log(1212, slug);
// This line caused the issue
// const dynamicPath = (`../../posts/${slug}.json`; // for eslint parsing error: "Cannot read property 'range' of null Occurred while linting"
const content = await import(`../../posts/${slug}.json`);
return {
props: {
jsonFile: {
fileRelativePath: `posts/${slug}.json`,
data: content.default,
},
},
};
}
/**
* The getStaticPaths function defines a list of paths that have
* to be rendered to HTML at build time.
*/
export async function getStaticPaths() {
//get all .json files in the posts dir
const posts = glob.sync('posts/**/*.json');
return {
paths: posts.map(file => ({
params: {
slug: `${file.replace('.json', '')}`,
},
})),
fallback: true,
};
}
添加回答
舉報