【发布时间】:2021-04-11 22:35:07
【问题描述】:
在/pages 我有[page].js 和index.js。
[page].js 通过“CustomPage”的值生成所需的页面。它的内容来自一个 Data-JSON-File。
只要我从主页开始并使用网页内的链接,它就可以正常工作。 例如,我现在有 2 个页面:/impressum 和 /datenschutz。
所以点击链接“Impressum”打开myDomain.com/impressum(它可以工作,但请注意,最后没有.html)。
但是,如果我刷新页面,或者直接在浏览器的地址栏中输入myDomain.com/impressum,我会收到一个未找到的错误(来自 nginx-server,而不是来自 next!)。
第二次尝试
由于我需要一个完全静态的页面,并且我在文件中添加了 getStaticPath 和 getStaticProps 以进行测试,因此将创建“真实”的 html 文件:
import { useRouter } from 'next/router';
import Index from './index';
import config from '../content/config.yml';
import CustomPage from '../src/components/CustomPage';
const RoutingPage = () => {
const { customPages } = config;
const router = useRouter();
const { page } = router.query;
const findMatches = (requestedPage) =>
customPages.find((customPage) => customPage.name === requestedPage) ||
false;
const customPageData = findMatches(page);
if (customPageData !== false) {
return <CustomPage pageContext={customPageData} />;
}
return page === 'index' ? (
<Index page={page} />
) : (
<p style={{ marginTop: '250px' }}>whats up {page}</p>
);
};
export async function getStaticPaths() {
return {
paths: [
{ params: { page: 'impressum' } },
{ params: { page: 'datenschutz' } },
],
fallback: false, // See the "fallback" section below
};
}
export async function getStaticProps({ params }) {
return { props: { page: params.page } };
}
export default RoutingPage;
但这导致我进入下一个问题: 我在网页中实现了内部链接,如下所示:
仍将用户引导至myDomain.com/impressum,现在还有myDomain.com/impressum.html 可用。从 SEO 的角度来看,这是两条不同的路径。
我如何将它们统一起来,这样我就只有一个路径 - 无论是从网页中打开还是直接输入。
解决方法想法 (??)
当然,我可以在任何地方使用类似的东西:
<Link href={`/${item.page}.html`}>
但这只有在页面被导出并复制到服务器时才有效。对于next dev 和next start,这是行不通的,因为.html 文件不存在....所以我在页面上工作时会丢失“页面预览”。
所以我唯一的想法是为.env.development 和.env.production 设置一个ENV-Variable,并将NEXT 中的-Component 封装在一个HOC 中。
在那个 HOC 中,我可以检查我当前是否处于开发或生产中,并且不要将 .html 用于这些链接......否则将 .html 添加到链接中。
你对此有何看法。您还有其他解决方案吗?
【问题讨论】:
标签: next.js getstaticprops getstaticpaths