I'm currently creating a SPA that can be included and run from any route.
Currently any <Link />
component I create redirects the client back to the root of the domain it's on plus the intended path.
In react-router
there's a property to set a starting base path; basename
.
This doesn't seem to be present in preact-router
and I'd really rather not switch to react-router
as it's significantly larger and I won't be using many of the additional features.
A simple example of the routes:
<Router>
<Route
path="/"
component={Home}
/>
<Route
path="/:slug"
component={Merchant}
/>
</Router>
I've seen a couple of post around the internet implying this is possible but with such little documentation it's a little tricky to piece together.
Any help is much appreciated.
Thanks.
I've ended up wrapping the preact-router
Link
and Router
with my own components. From there I can prefix the path
property value with my apps base route, eg:
<MyRoute
path="/"
component={Home}
/>
Then somewhere within <MyRoute />
:
const route = 'my/app/base/path';
let result = (route || '') + this.props.path;
result = result.replace(/([^:]\/)\/+/g, '$1');
Then render the preact-router
default component with the result value, <Route path={result} />
如果您正在寻找散列路由,请访问: https : //github.com/developit/preact-router#custom-history 。
jhdevuk's Answer pointed me to the right direction.
The following Router class will do the trick (this is in TypeScript):
class SubfolderRouter extends preactRouter.Router {
render(props: preactRouter.RouterProps, state: any) {
if (state.url.indexOf(MY_FOLDER) == 0) {
state = {
...state,
url: state.url.substr(MY_FOLDER.length),
};
}
return super.render(props, state);
}
}
If your app lives in the folder const MY_FOLDER = "/myfolder"
, then this Router will ignore the folder of the URL. If the user navigates to
/myfolder/home/index
then the Router will look up the URL /home/index
, because this is the actual route.
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.