I'm serving my site from /clientpanel
directory on my server. So my url is http://xxx.yy/clientpanel
. This is my client-side code:
const history = useRouterHistory(createHistory)({
basename: "/clientpanel"
});
render(
<Router history={history} routes={routes}/>,
document.getElementById("root")
);
On client-side everything works just fine. All urls are relative to /clientpanel
, but I have problem on how to get this work on server. This is my server-side code:
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))
}
});
On first page load I need to omit /clientpanel
in url to get this work, but then on client-side after clicking first <Link>
/clientpanel
is added to the begining. How to make it works consistent on both client and server side?
I finally got it to work with the following code:
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) => {
EDIT
Even better:
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 })
This doesn't work because createMemoryHistory doesn't have parameter basename.. The link will be different between client side and server side
I got a solution in the server side by replacing createHref like this :
import { createPath } from 'history/PathUtils';
[...]
history.createHref = location => '/' + language + createPath(location);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.