reactjs - Next.JS动态路由静态导出项目在新标签页打开或重新加载页面导致404

标签 reactjs apache next.js

我有一个带有 Apache + Cpanel 的 VPS。 我无法通过它配置 Nginx,所以据我所知,唯一的方法是先“静态导出”然后部署它。 原来我无法通过直接粘贴在 url 栏上的链接访问产品页面(而不是通过单击链接文本)。 链接看起来像这样:www.example.com/products/4www.example.com/products/213 我的第一个建议是因为我“静态导出”了项目。

我将 next-routes 与 <Link /> 结合使用

我的代码

import React, { Component } from 'react';
import { withRouter } from 'next/router';
import { connect } from 'react-redux';
import fetch from 'isomorphic-fetch';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import CheckoutBody from '../components/CheckoutBody';

class Product extends Component {
    static async getInitialProps({ query }) {
        let { id } = { ...query };
        if (id === undefined) id = 14;
        const res = await fetch(`http://www.example.com/api/product?id=${id}`);
        const data = await res.json();
        return { campaignDetail: data };
    }

    render() {
        let { lang } = this.props;

        return (
            <React.Fragment>
                <Navbar />
                <CheckoutBody
                    key={this.props.productDetail.id}
                    productDetail={this.props.productDetail}
                    lang={lang}
                />
                <Footer />
            </React.Fragment>
        );
    }
}

export default Product ;

同样的问题但不同的问题:https://github.com/zeit/next.js/issues/9893

我试过这个到 .htaccess。它不工作。我是正则表达式和 htaccess 的新手。

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule !.*\.html$ %{REQUEST_FILENAME}.html [L]
  1. 我该怎么办?
  2. 这就是所谓的动态路由吗?

最佳答案

该问题可能与使用下一次导出而不是重写规则配置有关。我们发现,如果您使用 next export,nextjs 路由器路径名在第一次命中时不会填充预期的路由。在 nextjs 解决此问题之前,您可以使用 _app.js 中的提供程序来包装您的组件并调整路由,或者将其放在 _app.js 默认函数中的 return 语句之前:

import { useRouter } from 'next/router'

const { asPath, push, pathname } = useRouter()
if (asPath.split('?')[0] != pathname.split('?')[0] && !pathname.includes('[')) {
    // Work around for next export breaking SPA routing on first hit
    console.log('Browser route ' + asPath + ' did not match nextjs router route ' + pathname)
    push(asPath)
    return <div>Loading...</div>
}

关于reactjs - Next.JS动态路由静态导出项目在新标签页打开或重新加载页面导致404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60226170/

相关文章:

PHP exec() 命令不会使用 sendkeys 启动 python 脚本

php - fatal error : Call to undefined function pg_connect()

javascript - firebase.initializeApp 在我的 dotenv 文件中找不到 API key 。 (下一个.js)

reactjs - Next.js/MSAL : Text does not match server-rendered html

javascript - 如何在 Reactjs 组件中使用普通 JavaScript?

javascript - Reactjs 源图

java - 如何使用 Apache Shiro 检查用户是否已经登录?

javascript - 在 Next.js 中避免重复的元描述和关键字

javascript - 多行文本以适应 React JS 中的父容器

javascript - 样式组件中的多个 Prop 检查