【问题标题】:Preact app using react router doesn't render routes in sub folder使用反应路由器的 Preact 应用程序不会在子文件夹中呈现路由
【发布时间】:2022-01-27 02:11:13
【问题描述】:

我有一个使用 react 路由器的 Preact 应用程序,并尝试从我的共享主机提供商的子文件夹中运行它。

当我加载网站时,第一条路线或任何后续路线都不会加载。仅加载主页和导航(并在点击时更改 url)。

我尝试在<Router basename="/company"/> 上使用basename="/company",但这似乎没有什么不同

我还创建了一个 .htaccess 文件,其中包含以下内容:

<IFModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /company
   RewriteRule ^index\.html$ - [L]
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-l
   RewriteRule . /index.html [L]
</IFModule>

但无法获取要加载的路线。我在控制台中看到他们正在尝试从服务器的根目录加载(domain.com/route-Colors.chunk.123abc.js),而不是他们所在的文件夹(domain.com/company/route-Colors.chunk.123abc.js)

为了让 Preact 和 react 路由器从我的共享主机提供商的子文件夹中加载初始视图和所有后续路由,我缺少什么?

【问题讨论】:

    标签: .htaccess react-router react-router-dom preact


    【解决方案1】:

    我假设这是一个 preact-cli 应用程序,虽然你没有说。

    这就是 Webpack 的 publicPath 所做的。您需要在配置文件中对其进行配置。

    preact.config.js

    export default (config, env, helpers) => {
        if (env.production) {
            config.output.publicPath = 'https://example.com/company';
        }
    }
    

    通常公共路径是/,因此它会尝试从根目录加载所有资产。

    【讨论】:

    • 这是我需要的顶级文件的目录重写,谢谢!!!但是,我还有另外两个相关问题:我有几个带有子路由的页面,例如&lt;Route exact path={["/colors", "/colors/:path"]} component={Colors}/&gt;,但是从/colors 页面上的选项卡中选择时它们不会加载。如何配置要加载的子路由?此外,当我从除第一个路由之外的任何路由重新加载页面时,该站点不会加载项目文件。我还需要添加什么才能解决上述问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2022-08-22
    • 2018-01-26
    • 2017-02-24
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多