我正在嘗試進行條件重定向,如果 url 中沒有“狀態”查詢引數,我想重定向到錯誤頁面。
我正在嘗試在我的 App.tsx 中執行此操作。由于此時我不能使用鉤子:useLocation 或 useHistory,我正在使用以下方式獲取查詢引數:
export default function App(): JSX.Element {
const urlQuery = new URLSearchParams(window.location.search);
const stateParam = urlQuery.get('state');
...
}
然后:
<BrowserRouter>
{!stateParam && <Redirect to="/error?state=1" />}
<Route path="/" exact component={HomeScreen} />
<Route path="/t1" exact component={T1Screen} />
<Route path="/t4" exact component={T4Screen} />
<Route path="/t2" exact component={T2Screen} />
<Route path="/t3" exact component={T3Screen} />
<Route path="/error" exact component={ErrorScreen} />
</BrowserRouter>
它正在作業,但是:
有沒有辦法對每條路線進行驗證(不在每個螢屏檔案中進行)?因為有幾個新頁面不需要狀態引數,錯誤螢屏也不應該需要狀態引數。
我想將驗證保存在一個地方,在 App.tsx 或另一個檔案中
uj5u.com熱心網友回復:
是的。由于您似乎使用的是react-router-domv5,因此您可以創建一個自定義Route組件來為您執行此檢查并有條件地呈現路由組件或重定向。
例子:
import { Redirect, useLocation } from 'react-router-dom';
const StateParamRoute = props => {
const { search } = useLocation();
const urlQuery = new URLSearchParams(search);
const stateParam = urlQuery.get('state');
return stateParam ? <Route {...props} /> : <Redirect to="/error?state=1" />;
};
使用StateParamRoute您希望進行此檢查的路線。
<BrowserRouter>
<Switch>
<StateParamRoute path="/t1" component={T1Screen} />
<StateParamRoute path="/t4" component={T4Screen} />
<StateParamRoute path="/t2" component={T2Screen} />
<StateParamRoute path="/t3" component={T3Screen} />
<Route path="/error" component={ErrorScreen} />
<Route path="/" component={HomeScreen} />
</Switch>
</BrowserRouter>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419273.html
標籤:
上一篇:根據另一個道具動態設定道具型別
下一篇:屬性'options'在'{question:number,label:string;型別中是可選的...etc}'但在型別'{question:an
