From 6409aa012b364d2b5a728e75f7c8e4b2b28b6265 Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Tue, 3 Aug 2021 19:04:40 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=B3=A8=E5=86=8C=E6=88=90?= =?UTF-8?q?=E5=8A=9F=E5=90=8E=E9=87=8D=E5=AE=9A=E5=90=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/src/hooks/useSearchParam.ts | 31 +++++++++++++++++++++++++++ web/src/routes/Entry/RegisterView.tsx | 12 +++++++++-- 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 web/src/hooks/useSearchParam.ts diff --git a/web/src/hooks/useSearchParam.ts b/web/src/hooks/useSearchParam.ts new file mode 100644 index 00000000..6328a7a9 --- /dev/null +++ b/web/src/hooks/useSearchParam.ts @@ -0,0 +1,31 @@ +import { useEffect, useState } from 'react'; + +const getValue = (search: string, param: string) => + new URLSearchParams(search).get(param); + +export type UseQueryParam = (param: string) => string | null; + +export const useSearchParam: UseQueryParam = (param) => { + const location = window.location; + const [value, setValue] = useState(() => + getValue(location.search, param) + ); + + useEffect(() => { + const onChange = () => { + setValue(getValue(location.search, param)); + }; + + window.addEventListener('popstate', onChange); + window.addEventListener('pushstate', onChange); + window.addEventListener('replacestate', onChange); + + return () => { + window.removeEventListener('popstate', onChange); + window.removeEventListener('pushstate', onChange); + window.removeEventListener('replacestate', onChange); + }; + }, []); + + return value; +}; diff --git a/web/src/routes/Entry/RegisterView.tsx b/web/src/routes/Entry/RegisterView.tsx index 33cfd41a..cbd8aef4 100644 --- a/web/src/routes/Entry/RegisterView.tsx +++ b/web/src/routes/Entry/RegisterView.tsx @@ -6,6 +6,8 @@ import { Icon } from '@iconify/react'; import { useHistory } from 'react-router'; import { setUserJWT } from '../../utils/jwt-helper'; import { setGlobalUserLoginInfo } from '../../utils/user-helper'; +import { useSearchParam } from '@/hooks/useSearchParam'; +import { isValidStr } from '../../../../shared/utils/string-helper'; /** * 注册视图 @@ -14,6 +16,7 @@ export const RegisterView: React.FC = React.memo(() => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const history = useHistory(); + const navRedirect = useSearchParam('redirect'); const [{ loading, error }, handleRegister] = useAsyncFn(async () => { await string() @@ -30,8 +33,13 @@ export const RegisterView: React.FC = React.memo(() => { setGlobalUserLoginInfo(data); await setUserJWT(data.token); - history.push('/main'); - }, [email, password]); + + if (isValidStr(navRedirect)) { + history.push(decodeURIComponent(navRedirect)); + } else { + history.push('/main'); + } + }, [email, password, navRedirect]); const toLoginView = useCallback(() => { history.push('/entry/login');