簡體   English   中英

React Router Link 不會在自定義歷史記錄中保留 state

[英]React Router Link doesn't keep state in custom history

在我的項目中,我使用 React Router DOM 5.2.0。 由於項目需要,我必須使用具有自定義歷史記錄的<Router /> 這是怎么回事:

沙盒示例

歷史.js

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

export default history;

使用Router.js

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;

AppRoutes.jsx

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;

應用程序.jsx

import history from './history';

<Router history={history}>
  <AppRoutes />
</Router>

這是基本設置。 Page1Page2是交叉鏈接組件,如下所示:

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處理。

系統:

  • Mac操作系統 11.4 大蘇爾
  • 節點12.16.2
  • NPM 6.14.11
  • 反應16.13.1
  • 反應路由器-dom 5.2.0

由於這篇文章https://stackoverflow.com/a/62583930/8080990 ,我剛剛找到了答案

降級到history版本 4,它完美運行!

沙盒

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM