繁体   English   中英

在服务器端的react-router中使用basename

[英]Use basename in react-router on server side

我正在服务器上的/clientpanel目录中提供我的站点。 所以我的网址是http://xxx.yy/clientpanel 这是我的客户端代码:

const history = useRouterHistory(createHistory)({
    basename: "/clientpanel"
});

render(
    <Router history={history} routes={routes}/>,
    document.getElementById("root")
);

在客户端,一切正常。 所有网址都与/clientpanel ,但我对如何在服务器上运行这个问题有/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之后在客户端添加到/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) => {

您需要提供匹配的基本名称:

match({ routes, location: req.url, basename: "/clientpanel" }, ...)

const history = createMemoryHistory({entries:[location],basename})

这不起作用,因为createMemoryHistory没有参数basename ..客户端和服务器端之间的链接会有所不同

通过替换createHref,我得到了服务器端的解决方案:

import { createPath } from 'history/PathUtils';
[...]
history.createHref = location => '/' + language + createPath(location);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM