簡體   English   中英

在組件外部的 react-router v5 中以編程方式訪問歷史記錄(history.push 等)

[英]Programmatic access to history (history.push etc) in react-router v5 outside of components

我曾經能夠在 <= v4 中將歷史記錄傳遞到 React Router:

import { Route } from 'react-router-dom';
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

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

編輯:我的錯,我之前使用的是Router ,而不是 SSR 所需的BrowserRouter BrowserRouter 可能從未給出過這個選項。 因此,似乎唯一的解決方案是拆分入口組件並從useHistory掛鈎獲取歷史記錄,然后將其傳遞給ApolloClient或其他任何內容。

投票結束。

也許我的代碼可以幫助你:

import { createBrowserHistory } from "history";
import qs from "qs";

const history = createBrowserHistory();

history.location = {
    ...history.location,
    query: qs.parse(history.location.search.substr(1)),
    state: {},
};
history.listen(() => {
    history.location = {
        ...history.location,
        query: qs.parse(history.location.search.substr(1)),
        state: history.location.state || {},
    };
});

const { go, goBack, push, replace } = history;

export { go, goBack, push, replace, getRedirectPath };
export default history;

然后在 react-router history 屬性中使用此文件中公開的歷史記錄。 現在,您可以在組件外部或內部使用公開的 go 或 push 函數。

謝謝,所以使用import { Router } from 'react-router-dom'; 相反,BrowserRouter 有幫助! 此外,您需要導入您的歷史記錄並作為道具傳遞給路由器: <Router history={history}>

然后 history.push 會重新渲染。

你可以試試

import { createBrowserHistory } from "history";

createBrowserHistory().push("/login");

它適用於“react-router-dom”:“^4.2.2”,似乎與您的問題無關

暫無
暫無

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

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