[英]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.