基本名称无法正常工作

aar*_*ron 10 react-router

我正在尝试使用react-router的基本名称,如react-router docs中所记录的那样.这是由于基础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')
);
Run Code Online (Sandbox Code Playgroud)

当我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;
}
Run Code Online (Sandbox Code Playgroud)

小智 7

这是我设法让它工作的方法

像这样将路由器基本名称设置为您的子目录

<Router basename="/subdirectory">

如果您使用 create-react-app 并使用 npm run build 进行构建,则需要在package.json 中设置 homepage以使生产构建中的路径正确

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;
}
Run Code Online (Sandbox Code Playgroud)


mau*_*uvm 5

我通过使用解决了它:

import { Router, useRouterHistory } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'

const history = useRouterHistory(createBrowserHistory)({
    basename: '/',
})

<Router history={history}>
Run Code Online (Sandbox Code Playgroud)

我认为问题是history软件包的不同版本。react-router@2.2.4使用history@2.1.2,而history已经在4.5.1。因此,请确保安装正确版本的history软件包。