4

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

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

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

在客户端,一切正常。所有 url 都相对于/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添加到开头。如何使其在客户端和服务器端工作一致?

4

3 回答 3

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) => {
于 2017-02-13T16:19:09.830 回答
2

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

match({ routes, location: req.url, basename: "/clientpanel" }, ...)
于 2017-02-13T14:24:35.383 回答
0

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

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

我通过像这样替换 createHref 在服务器端获得了解决方案:

import { createPath } from 'history/PathUtils';
[...]
history.createHref = location => '/' + language + createPath(location);
于 2018-10-25T10:08:31.000 回答