Как получить доступ к объекту истории вне компонентов (используя HashRouter)? - PullRequest
1 голос
/ 16 апреля 2020

Я прочитал документацию по реагирующему маршрутизатору здесь: https://github.com/ReactTraining/react-router/blob/master/FAQ.md#how -do-i-access-the-history-object-outside-of-Components

И статья решает решение с использованием Router; Тем не менее, мне нужно использовать HashRouter в моей реализации (для каждого бизнес-случая). Есть ли способ сделать это?

1 Ответ

0 голосов
/ 17 апреля 2020

Я делал это раньше, чтобы реализовать хранение истории страниц. Вы захотите сделать это во время вашей реакции на визуализацию.

Я просто добавил функции непосредственно к самому объекту истории. У меня нет опыта использования HashRouter, но это то, что я сделал с BrowserRouter. Вы можете даже передать избыточное хранилище своей функции createHistory или экземпляру любой «деловой» службы, которая может вам понадобиться. Или может иметь смысл даже передать сам экземпляр истории вашей бизнес-службе.

Пример:

import React from "react";

import { Provider } from "react-redux";
import ReactDOM from "react-dom";

import { createBrowserHistory } from "history";
import { Router, matchPath } from "react-router-dom";

import App from "./App";

// Function that handles creation of our redux store
import createStore from "./store";

// Function that handles creation of our custom history
// Would normally outsource this to its own file to be imported
const getFullURL = (location) => location.pathname + location.search;
export default (limit = 25) => {
  const history = createBrowserHistory();

  // Extend our history with a stack
  history.stack = [getFullURL(history.location)];

  // Add ability to listen to our history
  history.listen((location, action) => {
    const url = getFullURL(location);

    if (action === "REPLACE") {
      history.stack.pop();
    }

    history.stack.push(url);

    if (history.stack.length > limit) {
      history.stack.shift();
    }
  });

  // Extend our history with a function to go back to the
  //  most recent match route
  history.goToMostRecent = (routes, defaultPath = false) => {
    for (let i = history.stack.length - 1; i > -1; i--) {
      const path = history.stack[i];
      const strippedPath = path.split("?")[0];
      for (let j = 0; j < routes.length; j++) {
        const route = routes[j];
        const match = matchPath(strippedPath, {
          exact: true,
          path: route,
        });

        if (match) {
          history.push(path);
          return;
        }
      }
    }

    if (defaultPath) history.push(defaultPath);
  };

  return history;
};

const store = createStore();

// custom history with stack + extra actions
// could even pass in our store if we needed to access it for some reason
const history = createHistory();

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <App />
    </Router>
  </Provider>,
  document.getElementById("root")
);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...