【问题标题】:Use basename in react-router on server side在服务器端的 react-router 中使用 basename
【发布时间】:2016-11-10 13:11:26
【问题描述】:

我从服务器上的/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))
    }
});

在第一个页面加载时,我需要在 url 中省略 /clientpanel 才能完成这项工作,但是在首先单击 &lt;Link&gt; 后在客户端将 /clientpanel 添加到开头。如何让它在客户端和服务器端工作一致?

【问题讨论】:

  • 好像createMemoryHistory 不支持basename。您可以从req.url 中删除基本名称,它会起作用,但Links 仍然会损坏。

标签: javascript reactjs react-router server-side-rendering


【解决方案1】:

我终于让它与以下代码一起工作:

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) => {

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-06
        • 2016-05-24
        • 2019-02-03
        • 1970-01-01
        • 1970-01-01
        • 2016-03-26
        • 2015-08-18
        • 2016-11-17
        相关资源
        最近更新 更多