[英]NextJs Fetching Copy Text from a data file
我是 NextJs 和 React 的新手。 我正在編寫一個網站,並希望能夠將所有復制文本(網站用戶看到的文本)存儲在一個中央數據文件中,並動態地將其調用到每個部分/組件元素中。
我走這條路而不是將 static 文本硬編碼到每個元素中的原因是我使用文案來編輯我的文本。 因此,我希望能夠向此人發送一個包含所有站點文本的簡單文件以供編輯,而無需讓編輯器提供或訪問整個站點代碼。
我想我應該為此目的在 NextJs 中使用getStaticProps
function :
export async function getStaticProps(context) {
const res = await fetch(`../data/copy.data.js`);
const data = await res.json();
if (!data) {
return {
notFound: true
};
}
return {
props: { data } // will be passed to the page component as props
};
}
連同將保存每個部分復制文本作為屬性的 Jason 文件。 像copy.data.js這樣的東西
export const copyText = [
{
id: 1,
section: "Hero",
Header: "The Heading Text",
SubHeading: "SubHeading Text",
Body: "The Body paragragh of text which has a lot more to say"
},
{
id: 2,
section: "Feature",
Header: "Feature Heading",
SubHeading: "Feature SubHeading",
Body: "The Body paragragh of text which has a lot more to say"
},
{
id: 3,
section: "Services",
Header: "Services Heading",
SubHeading: "Services SubHeading",
Body: "The Body paragragh of text which has a lot more to say"
},
{
id: 4,
section: "Service",
Header: "Service Heading",
SubHeading: "Service SubHeading",
Description: "The Specific Service Description paragragh"
},
];
然后在我的組件中使用如下數據:
<section sx={styles.section} className="Hero">
{copyText.map ((copyItem, 1) => (
<Header sx={styles.header}>{copyItem.Header}</Header>
<SubHeading sx={styles.header}>{copyItem.SubHeading}</SubHeading>
<Text sx={styles.header}>{copyItem.Body}</Text>
</section>
我不確定這是否是 go 的正確方法,或者我是否有更簡單的方法來實現。
如果我們使用上面介紹的fetch
function,我們會得到一個錯誤:
服務器錯誤
TypeError:僅支持絕對 URL
為避免此錯誤,代碼應如下所示(這是我的主觀主張):演示文稿盡可能簡單,您可以嘗試根據自己的需要調整代碼。
data.js
文件位於項目root
目錄中。 在id:4
中,我將最后一項從Description
更改為Body
以保持一致;-)
index.js (主頁)
import ItemsList from "../components/ItemsList.js";
import { copyText } from "../data.js";
export default function Home({ data }) {
// console.log(data);
return (
<div className="center">
<ItemsList data={data} />
</div>
);
}
export async function getStaticProps() {
return {
props: { data: copyText }, // will be passed to the page component as props
};
}
ItemsList.js
import Items from "./Items";
function ItemsList({ data }) {
return (
<>
<ul className="center">
{data.map((event) => (
<Items
key={event.id}
id={event.id}
section={event.section}
header={event.Header}
subHeading={event.SubHeading}
body={event.Body}
/>
))}
</ul>
</>
);
}
export default ItemsList;
項目.js
function Items({ id, section, header, subHeading, body }) {
return (
<div className="card">
<small>{id}</small>
<h4>{section}</h4>
<h1>{header}</h1>
<h2>{subHeading}</h2>
<p>{body}</p>
</div>
);
}
export default Items;
當然我添加了一些css
,但我不會展示它,因為這不是重點。
在 Win10 上測試“next”:“12.0.4”,“react”:“17.0.2”,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.