我正在尝试使用一个带有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;
}发布于 2018-03-22 05:07:09
下面是我是如何让它工作的
将Router basename设置为您的子目录,如下所示
<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;
}发布于 2017-02-15 20:03:30
我通过使用以下命令解决了这个问题:
import { Router, useRouterHistory } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
const history = useRouterHistory(createBrowserHistory)({
basename: '/',
})
<Router history={history}>我认为问题出在history包的不同版本上。react-router@2.2.4使用history@2.1.2,而history已经在4.5.1上了。因此,请确保安装了正确版本的history包。
发布于 2020-04-01 16:36:08
使用BrowserRouter的
helpers/history.js
import { createBrowserHistory } from "history";
export default createBrowserHistory();index.js
import {BrowserRouter as Router} from "react-router-dom";
import history from "helpers/history";
.....
<Router history={history} basename={'/app'}>
...
</Router>使用路由器的
helpers/history.js
import { createBrowserHistory } from "history";
export default createBrowserHistory({ basename: '/app' });index.js
import {Router} from "react-router-dom";
import history from "helpers/history";
....
<Router history={history}>
...
</Router>https://stackoverflow.com/questions/37887409
复制相似问题