[英]React Router Link doesn't keep state in custom history
在我的項目中,我使用 React Router DOM 5.2.0。 由於項目需要,我必須使用具有自定義歷史記錄的<Router />
。 這是怎么回事:
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;
import {
useParams,
useRouteMatch,
} from 'react-router-dom';
import { useMemo } from 'react';
import history from './history';
import urlQueriesService from './urlQueriesService';
const useRouter = () => {
const params = useParams();
const match = useRouteMatch();
const { location } = history;
return useMemo(() => ({
push: history.push,
replace: history.replace,
pathname: location?.pathname,
query: {
...urlQueriesService.parse(location?.search),
...params,
},
match,
location,
history,
}), [params, match, location, history]);
};
export default useRouter;
import React from 'react';
import {
Route,
Switch,
} from 'react-router-dom';
import useRouter from './useRouter';
import TestPage from './TestPage';
import TestComponent from './TestComponent';
const AppRoutes = () => {
const { location } = useRouter();
return (
<Switch location={location}>
<Route exact path="/page-1" component={Page1} />
<Route exact path="/page-2" component={Page2} />
</Switch>
);
};
export default AppRoutes;
import history from './history';
<Router history={history}>
<AppRoutes />
</Router>
這是基本設置。 Page1
和Page2
是交叉鏈接組件,如下所示:
import React from 'react';
import { Link } from 'react-router-dom';
import useRouter from './useRouter';
const Page1 = () => {
const { location } = useRouter();
return (
<div>
<h1>Test</h1>
<div>
<Link to={{ pathname: '/page-2', state: { prevUrl: location.pathname }}}>Stateful component</Link>
</div>
</div>
);
};
export default Page1;
這里的關鍵部分是Link
組件,它必須to
object 為值。 在這個 object 中,我定義state: { prevUrl: location.pathname }
,但是當我嘗試在Page2
中訪問它時,這個state
總是null
。 這里有趣的是,如果我將<Router />
更改為BrowserRouter
並從Switch
中刪除自定義location
- 一切正常,這意味着<Link />
確實傳播了 state。然而,在我的例子中,它看起來像 state 不是完全由history
處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.