我正在服务器上的/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
以使其工作,但在首先点击<Link>
/clientpanel
之后在客户端添加到开头。如何使它在客户端和服务器端都能保持一致?
答案 0 :(得分:4)
我终于使用以下代码:
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) => {
答案 1 :(得分:2)
您需要提供匹配的基本名称:
match({ routes, location: req.url, basename: "/clientpanel" }, ...)
答案 2 :(得分:0)
const history = createMemoryHistory({entry:[location],basename})
这不起作用,因为createMemoryHistory没有参数basename。.客户端和服务器端的链接将不同
我在服务器端找到了一个解决方案,方法是像这样替换createHref:
import { createPath } from 'history/PathUtils';
[...]
history.createHref = location => '/' + language + createPath(location);