我尝试使用带有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')
);
&#13;
当我转到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;
}
答案 0 :(得分:3)
将路由器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;
}
答案 1 :(得分:2)
我通过使用:
解决了它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
包的正确版本。
答案 2 :(得分:0)
使用BrowserRouter
helpers / history.js
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setPaint(new TexturePaint(slate, new Rectangle(getWidth()/3,20,this.getWidth()*3/5,
this.getHeight()/8)));
g2d.fillRect(getWidth()/3, 20, this.getWidth()*3/5, this.getHeight()/8);
}
index.js
import { createBrowserHistory } from "history";
export default createBrowserHistory();
使用路由器
helpers / history.js
import {BrowserRouter as Router} from "react-router-dom";
import history from "helpers/history";
.....
<Router history={history} basename={'/app'}>
...
</Router>
index.js
import { createBrowserHistory } from "history";
export default createBrowserHistory({ basename: '/app' });