custom router use pathToRegexp

This commit is contained in:
NikolaBorislavovHristov 2018-07-02 14:23:18 +03:00
parent ffec89d3cc
commit 10c2854acb
2 changed files with 17 additions and 13 deletions

View file

@ -5,12 +5,12 @@ const config = {
{ {
routes: [ routes: [
{ {
path: '/calendar', path: '/',
component: Calendar component: Board
}, },
{ {
path: '/board', path: '/calendar',
component: Board component: Calendar
} }
] ]
}, },

View file

@ -1,6 +1,6 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import { matchPath } from 'react-router-dom'; import pathToRegexp from 'path-to-regexp';
import { join as joinPaths } from 'path'; import PathUtils from 'path';
class Router extends Component { class Router extends Component {
constructor(props) { constructor(props) {
@ -30,18 +30,24 @@ class Router extends Component {
onLocationChanged = () => { onLocationChanged = () => {
const hashIndex = window.location.href.indexOf('#'); const hashIndex = window.location.href.indexOf('#');
const hashPath = hashIndex === -1 ? '' : window.location.href.substring(hashIndex + 1); const hashPath = hashIndex === -1 ? '' : window.location.href.substring(hashIndex + 1);
const path = joinPaths('/', hashPath); const path = PathUtils.join('/', hashPath);
if (hashPath !== path) { if (hashPath !== path) {
window.location.replace(`#${path}`); window.location.replace(`#${path}`);
return; return;
} }
let pathMatched = false;
for (let viewConfigIndex = 0; viewConfigIndex < this.props.config.views.length; viewConfigIndex++) { for (let viewConfigIndex = 0; viewConfigIndex < this.props.config.views.length; viewConfigIndex++) {
const viewConfig = this.props.config.views[viewConfigIndex]; const viewConfig = this.props.config.views[viewConfigIndex];
for (const routeConfig of viewConfig.routes) { for (const routeConfig of viewConfig.routes) {
if (matchPath(path, routeConfig)) { const keys = [];
pathMatched = true; const regexp = pathToRegexp(routeConfig.path, keys, {
strict: false,
sensitive: false,
end: true,
...routeConfig.options
});
const match = regexp.exec(path);
if (match) {
this.setState(({ views }) => ({ this.setState(({ views }) => ({
views: views.map((view, viewIndex) => { views: views.map((view, viewIndex) => {
if (viewIndex > viewConfigIndex) { if (viewIndex > viewConfigIndex) {
@ -64,9 +70,7 @@ class Router extends Component {
} }
} }
if (!pathMatched) { window.location.replace('#/');
window.location.replace('#/');
}
} }
render() { render() {