我正在尝试将基本名称与 react-router 一起使用,如记录的 on the react-router docs 。这是因为 base href 已被弃用。

这是我现在所拥有的:

import { Route, Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';
import { render } from 'react-dom';

var history = useRouterHistory(createHistory)({
  basename: '/subdirectory'
});

render(
  <Router history={history}>
    <Route path='/' component={App}>
      <Route path='next' component={Next} />
    </Route>
  </Router>,
  document.getElementById('root')
);


当我转到 http://the-url.com/subdirectory 时,页面按预期加载(呈现 App 组件)。但是,当转到 http://the-url.com/subdirectory/next 时,出现 404 错误。我的 nginx 配置是:
location /subdirectory {
  alias /path/to/index.html;
  index index.html;
  try_files $uri $uri/ /path/to/index.html;
}

最佳答案

这是我设法让它工作的方法
像这样将路由器基本名称设置为您的子目录<Router basename="/subdirectory">如果您使用 create-react-app 并使用 npm run build 进行构建,则需要在 package.json 中设置主页,以使生产版本中的路径正确homepage: "{http://www.the-url.com/subdirectory}"对于 nginx 配置,假设您的 index.html 在 /path/to/subdirectory/index.html 下。那么以下应该工作

location /subdirectory {
    root /path/to;
    try_files $uri $uri/ /subdirectory/index.html;
}

关于react-router - Basename 无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37887409/

10-13 07:20