在wordpress中反应路由

问题描述 投票:0回答:2

我正在构建一个以Wordpress作为后端运行的反应SPA,但它并非无头,因此整个前端都包含在主题中。我只需运行npm build并将functions.php文件中的生产文件排入队列。应用程序在模板文件中呈现为<div id="root"></div>。我的wordpress安装设置为具有静态主页,该主页使用包含React根div的模板。

除路由器外,这似乎工作得很好。如果我去一个不同的地址,比如https://mywebsite/about,它会尝试加载一个名为about的wordpress页面,而不是停留在同一页面上,并使用路由器渲染相应的组件。我必须在.htaccess文件中更改某些设置吗?或者还有其他我想念的东西?

wordpress reactjs .htaccess react-router
2个回答
0
投票

是的,答案在.htaccess文件中。

您需要设置一个catchall规则,它将为所有路由提供index.php文件,而不是试图找到现在正在发生的路由的匹配php文件。

您应该能够使用此配置来实现此类行为:

# BEGIN WordPress

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

# END WordPress

解决方案确实意味着您在服务器上使用modrewrite。


1
投票

如果您的WP页面上有React应用程序并且您不想编辑.htaccess,您还可以在functions.php中添加重写规则和add_rewrite_rule(),以将所有请求重定向到您的反应应用程序WP页面,由React路由器处理。

add_action('init', 'wp55290310_rewrite_rules');

function wp55290310_rewrite_rules() {
    add_rewrite_rule('^your-react-app-root/(.+)?', 'index.php?pagename=your-react-page-name', 'top');
}

您需要在React Router中指定baseName:

<BrowserRouter basename="/your-react-app-root">
  <Switch>
      <Route exact path="/" component={SomeComponent} />
      <Route exact path="/other-page" component={OtherComponent} />
  </Switch>
</BrowserRouter>
© www.soinside.com 2019 - 2024. All rights reserved.