Gathering detailed insights and metrics for direct-react-router
Gathering detailed insights and metrics for direct-react-router
Gathering detailed insights and metrics for direct-react-router
Gathering detailed insights and metrics for direct-react-router
npm install direct-react-router
Typescript
Module System
Node Version
NPM Version
TypeScript (99.62%)
JavaScript (0.38%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
5 Stars
74 Commits
1 Forks
3 Watchers
9 Branches
2 Contributors
Updated on Dec 17, 2020
Latest Version
2.0.0
Package Id
direct-react-router@2.0.0
Unpacked Size
31.22 kB
Size
9.31 kB
File Count
23
NPM Version
6.4.1
Node Version
10.15.2
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
componentDidMount
)react-router
, а можно и не использовать 😋)1npm i direct-react-router
Зависимости: react ^16.8.6
, redux ^4.0.1
, react-redux ^7.0.0
, history ^5.0.0
.
Конфигурация задает плоский список роутов и алиасы для них. Также вам понадобится экземпляр history
.
1import { createBrowserHistory } from 'history'; 2import { RouterConfig } from 'direct-react-router'; 3 4const history = createBrowserHistory(); 5 6const config: RouterConfig = { 7 routes: { 8 PAGE1: '/p1', 9 PAGE2: '/p2/:login/count/:num' 10 } 11};
Синтакис шаблонов путей:
1const config: RouterConfig = { 2 routes: { 3 EXAMPLE1: '/:foo/:bar', // named parameters 4 EXAMPLE2: '/:foo/:bar?', // optional parameters 5 EXAMPLE3: '/:foo*', // zero or more 6 EXAMPLE4: '/:foo+', // one or more 7 8 // see details: https://npmjs.org/package/path-to-regexp 9 } 10};
При сравнении всегда
exact === true
, поэтому порядок описания роутов не важен. Если текущему URL соответствует несколько роутов, будет исключение.
1import { createRoutingMiddleware } from 'direct-react-router';
2// ...
3const routerMiddleware = createRoutingMiddleware(config, history);
4// ...
5const store = createStore(rootReducer, routerMiddleware);
Теперь при каждом изменении url будет генериироваться action, который вы можете обрабатывать любым нужным способом. В него приходит информация о новом URL и его параметрах + его alias в конфиге.
1/* 2{ 3 type: '@@direct-react-router/LOCATION_CHANGED', 4 location: { 5 key: '<route key>', 6 pathname: '...', 7 search: '...', 8 hash: '...', 9 params: { ... }, 10 query: { ... } 11 }, 12 action: 'PUSH' 13} 14*/
Вы можете подключить готовый редюсер, который будет обрабатывать события изменения URL и класть информацию в state. Также он отвечает за начальное состояние (начальный url).
1import { RouterLocation, createRoutingReducer } from 'direct-react-router'; 2 3export interface State { 4 location: RouterLocation; 5 // ... 6} 7 8const rootReducer = combineReducers({ 9 location: createRoutingReducer( 10 config, // конфиг роутера 11 history.location // начальный url 12 ), 13 // ... 14});
1import { Link } from 'direct-react-router'; 2// ... 3 4render() { 5 const href = '/p2/test/count/12?aa=1&bb=2#xxx'; 6 return <Link href={href}>page1</Link>; 7} 8 9/* 10location: { 11 pathname: '/p2/test/count/12', 12 search: '?aa=1&bb=2', 13 hash: '#xxx', 14 key: 'PAGE2', 15 params: { login: 'test', num: '12' }, 16 query: { aa: '1', bb: '2' } 17} 18*/ 19
1import { AdvancedLink, RouterContext } from 'direct-react-router'; 2// ... 3 4render() { 5 return ( 6 <Provider store={store}> 7 <RouterContext.Provider value={{ config }}> 8 ... 9 <AdvancedLink 10 routeKey='PAGE2' 11 params={{ login: 'test', num: '12' }} 12 query={{ aa: '1', bb: '2' }} 13 hash='#xxx' 14 > 15 page2 16 </AdvancedLink> 17 ... 18 </RouterContext.Provider> 19 </Provider> 20 ); 21} 22 23/* 24href: 25 /p2/test/count/12?aa=1&bb=2#xxx 26location: { 27 pathname: '/p2/test/count/12', 28 search: '?aa=1&bb=2', 29 hash: '#xxx', 30 key: 'PAGE2', 31 params: { login: 'test', num: '12' }, 32 query: { aa: '1', bb: '2' } 33} 34*/ 35
Внимание! проверьте, что нет лишних перерисовок
Через пропсы компонентов Link
и AdvancedLink
можно настраивать параметры обращения к history api:
replace?: boolean
- использовать REPLACE
(по умолчанию PUSH
)state?: object | null
- объект состояния, ассоциированный с новой записью истории браузераforceReload?: boolean
- перезагружать страницу при переходе по ссылкеВезде работаем с относительными путями.
basename
в createBrowserHistory
.basename
через контекст.1import { Link, RouterContext } from 'direct-react-router'; 2// ... 3const basename = 'your/base/path'; 4 5// учитываем basename при обработке url 6const history = createBrowserHistory({ basename }); 7 8 9render() { 10 return ( 11 // учитываем basename при генерации url для ссылок 12 <RouterContext.Provider value={{ basename }}> 13 ... 14 <Link href='/test/xxx' /> 15 ... 16 </RouterContext.Provider> 17 ); 18} 19 20/* 21href: 22 /your/base/path/test/xxx 23location: { 24 pathname: '/test/xxx', 25 ... 26} 27*/
Middleware генерирует экшены при изменении url в адресной строке. При открытии страницы экшен с текущим url по умолчанию не генерируется. Если он вам нужен, сгенерируйте его руками.
1import { parseLocation, changeLocation } from 'direct-react-router';
2// ...
3
4const routerLocation: RouterLocation = parseLocation(config, history.location);
5store.dispatch(changeLocation(routerLocation));
?
в query stringMIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 2/27 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
23 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More