Skip to content

Commit a70f7e5

Browse files
authored
[draft] possible "why not both" solution for route param-to-prop mapping
![https://media.tenor.com/images/cf17987a71bae395fb62323f92ecb99e/tenor.gif](why not both?)
1 parent de324dc commit a70f7e5

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

router.js

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,23 +32,22 @@ const UPDATE = (state, url) => {
3232
export const exec = (url, route, matches) => {
3333
url = url.split('/').filter(Boolean);
3434
route = (route || '').split('/').filter(Boolean);
35-
const params = matches.params || (matches.params = {});
36-
for (let i = 0, val; i < Math.max(url.length, route.length); i++) {
35+
for (let i = 0, val, rest; i < Math.max(url.length, route.length); i++) {
3736
let [, m, param, flag] = (route[i] || '').match(/^(:?)(.*?)([+*?]?)$/);
3837
val = url[i];
3938
// segment match:
4039
if (!m && param == val) continue;
4140
// segment mismatch / missing required field:
4241
if (!m || (!val && flag != '?' && flag != '*')) return;
43-
// field match:
44-
params[param] = val && decodeURIComponent(val);
45-
// normal/optional field:
46-
if (flag >= '?' || flag === '') continue;
42+
rest = flag == '+' || flag == '*';
4743
// rest (+/*) match:
48-
matches[param] = url.slice(i).map(decodeURIComponent).join('/');
49-
break;
44+
if (rest) val = url.slice(i).map(decodeURIComponent).join('/');
45+
// normal/optional field:
46+
else if (val) val = decodeURIComponent(val);
47+
matches.params[param] = val;
48+
if (param != 'ref' && param != 'key' && param != 'path' && param != 'query' && param != 'params') matches[param] = val;
49+
if (rest) break;
5050
}
51-
5251
return matches;
5352
};
5453

@@ -108,7 +107,7 @@ export function Router(props) {
108107

109108
let p, d, m;
110109
toChildArray(props.children).some(vnode => {
111-
const matches = exec(path, vnode.props.path, (m = { path, query }));
110+
const matches = exec(path, vnode.props.path, (m = { path, query, params: {} }));
112111
if (matches) return (p = cloneElement(vnode, m));
113112
if (vnode.props.default) d = cloneElement(vnode, m);
114113
});

0 commit comments

Comments
 (0)