javascript – 在服务器端的react-router中使用basename
作者:互联网
我正在服务器上的/ 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))
}
});
在第一页加载时,我需要在url中省略/ clientpanel以使其工作,但是在首先单击< 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,reactjs,react-router,serverside-rendering 来源: https://codeday.me/bug/20190527/1165338.html