Skip to content

Commit 36b42c5

Browse files
committed
fix: fix unexpected 404 page rendering on first visit
1 parent 23cd52a commit 36b42c5

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

src/router/components/Router/index.tsx

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ import { Freeze } from 'react-freeze'
33

44
import { createBrowserHistory, createHashHistory, History } from 'history'
55

6+
import { WAITING_FIRST_MATCH } from '../../constants/global'
67
import { LocationContext } from '../../context/LocationContext'
78
import { NavigationContext } from '../../context/NavigationContext'
89
import { RouteContext } from '../../context/RouteContext'
9-
import { ProHistory, ProInfo } from '../../core/history'
10+
import { ProHistory, ProInfo, ProSubscriber } from '../../core/history'
1011
import { MatchRecord, Route } from '../../core/route'
1112
import useCreation from '../../hooks/useCreation'
1213
import NotFound from '../NotFound'
@@ -15,6 +16,7 @@ export type ErrorInfo = {
1516
type: '404'
1617
error?: Error
1718
}
19+
1820
export type ErrorHandler = (info: ErrorInfo) => ReactNode | void
1921

2022
export type RouterProps = {
@@ -28,6 +30,11 @@ const renderRoutes = (records: MatchRecord[], handleError?: ErrorHandler) => {
2830
const { length } = records
2931

3032
if (length < 1) {
33+
// TODO: insert loading?
34+
if (WAITING_FIRST_MATCH.value) {
35+
return null
36+
}
37+
3138
return handleError?.({ type: '404' }) || <NotFound />
3239
}
3340

@@ -57,6 +64,7 @@ export const Router = ({
5764
location: history.location,
5865
records: []
5966
})
67+
6068
const proHistory = useCreation(
6169
{
6270
factory: () =>
@@ -66,6 +74,8 @@ export const Router = ({
6674
[basename, history, routes]
6775
)
6876

77+
console.log(records)
78+
6979
const children = renderRoutes(records, onError)
7080

7181
return (

src/router/constants/global.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// 初始化阶段,还没开始匹配路由
2+
export const WAITING_FIRST_MATCH = {
3+
value: true
4+
}

src/router/core/history.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createPath, History, Location, parsePath, Path, To } from 'history'
22

3+
import { WAITING_FIRST_MATCH } from '../constants/global'
34
import { isLazyComponent, loadLazyComponent } from '../utils/component'
45
import { Noop } from '../utils/function'
56
import {
@@ -163,6 +164,9 @@ export class ProHistory {
163164
return
164165
}
165166

167+
// 允许渲染 404 页面
168+
WAITING_FIRST_MATCH.value = false
169+
166170
const path = stripBasename(this.basename, pathname)
167171

168172
if (!path) {

0 commit comments

Comments
 (0)