我从 /clientpanel
为我的网站提供服务我服务器上的目录。所以我的网址是 http://xxx.yy/clientpanel
.这是我的客户端代码:
const history = useRouterHistory(createHistory)({
basename: "/clientpanel"
});
render(
<Router history={history} routes={routes}/>,
document.getElementById("root")
);
在客户端,一切正常。所有网址都相对于 /clientpanel
,但我对如何在服务器上进行这项工作有疑问。这是我的服务器端代码:
const history = useRouterHistory(createMemoryHistory)({
basename: "/clientpanel"
});
match({ routes, location: req.url, history}, (error, redirectLocation, renderProps) => {
if (renderProps) {
const html = renderToString(
<RouterContext {...renderProps}/>
);
res.send(renderFullPage(html))
}
});
在第一页加载时,我需要省略 /clientpanel
在 url 中进行这项工作,但在先单击 <Link>
后在客户端进行/clientpanel
被添加到开头。如何使其在客户端和服务器端工作一致?
最佳答案
我终于让它可以使用以下代码:
const basename = '/foo'
const location = req.url.replace(basename, '')
// createMemoryHistory from the history package
const history = useRouterHistory(() => createMemoryHistory(location))({ basename })
match({ history, routes, location }, (error, redirectLocation, renderProps) => {
编辑
更好的是:
const basename = '/foo'
const location = req.url.replace(basename, '')
// createMemoryHistory from the react-router package
const history = createMemoryHistory({ entries: [location], basename })
match({ history, routes, location }, (error, redirectLocation, renderProps) => {
关于javascript - 在服务器端的 react-router 中使用 basename,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40528489/