source

react-router를 사용하여 브라우저에서 /#/을(를) 중지하는 방법

nicesource 2023. 3. 10. 22:06
반응형

react-router를 사용하여 브라우저에서 /#/을(를) 중지하는 방법

「 」를 막기 의 방법/#/브라우저의 주소 표시줄에 표시되지 않도록 하려면 어떻게 해야 합니까? 이동하기 링크를 하면 "J"가 표시됩니다.localhost:3000/#/ ★★★★★★★★★★★★★★★★★」localhost:3000/#/about루트에 따라 다릅니다.

리액트 라우터가 몇 번이고 리팩터링을 거듭함에 따라 이 질문에 대한 답변은 몇 년 동안 극적으로 바뀌었습니다.각 버전의 문제를 해결하는 방법에 대한 자세한 내용은 다음과 같습니다.

버전 6

를 " 라우터입니다.는 " 라우터"를 하여 작성됩니다.이 라우터는createBrowserRouter()앱의 됩니다.반응하다

import React from "react";
import ReactDOM from "react-dom/client";
import {
  createBrowserRouter,
  RouterProvider,
  Route,
} from "react-router-dom";

const router = createBrowserRouter([
  {
    path: "/",
    element: ...,
  },
]);

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

소스 리액트 라우터 버전6 문서:

버전 4

react-router 해야 합니다.BrowserRouter이치노

import BrowserRouter from 'react-router/BrowserRouter'
ReactDOM.render (( 
  <BrowserRouter>
   ...
 <BrowserRouter> 
), document.body);

할 수 되지 않습니다. 이 버전 6에서는 사용할 수 없습니다.BrowserRouter리액트 라우터 API를 사용합니다.

소스 리액트 라우터 버전4 문서

버전 2 및 3

Router2, 매핑 은 이력 을 React Router 1, 2, 3에 전달하는 것입니다.history「」<Router>. 이력 문서:

간단히 말해, 이력은 브라우저의 주소 표시줄에서 변경 내용을 청취하는 방법을 알고 URL을 라우터가 루트를 대조하고 올바른 컴포넌트 세트를 렌더링하기 위해 사용할 수 있는 위치 개체로 해석합니다.

리액트 라우터2 및 3에서는 루트컨피규레이션코드는 다음과 같습니다.

import { browserHistory } from 'react-router'
ReactDOM.render (( 
 <Router history={browserHistory} >
   ...
 </Router> 
), document.body);

버전 1

버전 1.x에서는 대신 다음 명령을 사용합니다.

import createBrowserHistory from 'history/lib/createBrowserHistory'
ReactDOM.render (( 
  <Router history={createBrowserHistory()} >
   ...
  </Router> 
), document.body);

출처: 버전 2.0 업그레이드 가이드

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

0.에는 0.11을 추가해야 .Router.HistoryLocation로로 합니다.Router.run()<Routes>는 폐지되었습니다.0.12.x HistoryLocation 실장에 대해서는, 「업그레이드 가이드」를 참조해 주세요.

없는 경우 할 수 는 IE8을 합니다.window.pushState해시를 설정하는 대신.

정확한 방법은 사용 중인 React Router 버전에 따라 달라집니다.

  • v4: https://reacttraining.com/react-router/web/api/BrowserRouter
  • v3: https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md
  • v2: https://github.com/ReactTraining/react-router/blob/v2.0.0/docs/guides/Histories.md
  • v1: https://github.com/ReactTraining/react-router/blob/1.0.x/docs/guides/basics/Histories.md

실제로 .htaccess를 사용하여 이 작업을 수행할 수 있습니다.일반적으로 브라우저에는 쿼리 문자열 구분 기호가 필요합니다.?또는#쿼리 문자열이 시작되고 디렉토리 경로가 끝나는 위치를 결정합니다.우리가 원하는 최종 결과는www.mysite.com/dir따라서 웹 서버가 요청한 디렉토리를 검색하기 전에 문제를 파악해야 합니다./dir. 그래서 우리는 a를 배치한다..htaccess파일을 프로젝트의 루트에 저장합니다.

    # Setting up apache options
    AddDefaultCharset utf-8
    Options +FollowSymlinks -MultiViews -Indexes
    RewriteEngine on

    # Setting up apache options (Godaddy specific)
    #DirectoryIndex index.php
    #RewriteBase /


    # Defining the rewrite rules
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteCond %{SCRIPT_FILENAME} !-f

    RewriteRule ^.*$ ./index.html

그런 다음 window.location.pathname을 사용하여 쿼리 파라미터를 가져옵니다.

필요에 따라 리액트루트를 사용하지 않고 필요에 따라 URL 및 브라우저 이력만 조작할 수 있습니다.이게 도움이 됐으면 좋겠는데...

이력 패키지 설치

npm install history --save

다음으로 createHistory와 useBasename을 이력에서 Import합니다.

import { createHistory, useBasename } from 'history';
...
const history = useBasename(createHistory)({
  basename: '/root' 
});

앱 URL이 www.example.com/myApp,인 경우 /root은 /myApp이어야 합니다.

이력 변수를 라우터에 전달하다

render((
  <Router history={history}>
    ...
  </Router>
), document.getElementById('example'));

모든 링크 태그에 대해 모든 경로 앞에 "/"를 추가합니다.

<Link to="/somewhere">somewhere</Link>

이 솔루션의 영감은 React-Router의 예에서 나왔는데 안타깝게도 API에 제대로 문서화되지 않았습니다.

해시 후에 표시하는 다른 방법(따라서 pushState!를 사용하지 않는 경우)은 CustomLocation을 생성하여 ReactRouter 작성 시 로드하는 것입니다.

예를 들어, 구글의 크롤링 사양에 준거하기 위해서 해시방 URL(#!)을 사용하는 경우는, 다음과 같은 원래의 HashLocation을 주로 카피하는 HashbangLocation.js 파일을 작성할 수 있습니다.

'use strict';

var LocationActions = require('../../node_modules/react-router/lib/actions/LocationActions');
var History = require('../../node_modules/react-router/lib/History');

var _listeners = [];
var _isListening = false;
var _actionType;

function notifyChange(type) {
  if (type === LocationActions.PUSH) History.length += 1;

  var change = {
    path: HashbangLocation.getCurrentPath(),
    type: type
  };

  _listeners.forEach(function (listener) {
    listener.call(HashbangLocation, change);
  });
}

function slashToHashbang(path) {
  return "!" + path.replace(/^\//, '');
}

function ensureSlash() {

  var path = HashbangLocation.getCurrentPath();
  if (path.charAt(0) === '/') {
    return true;
  }HashbangLocation.replace('/' + path);

  return false;
}

function onHashChange() {
  if (ensureSlash()) {
    // If we don't have an _actionType then all we know is the hash
    // changed. It was probably caused by the user clicking the Back
    // button, but may have also been the Forward button or manual
    // manipulation. So just guess 'pop'.
    var curActionType = _actionType;
    _actionType = null;
    notifyChange(curActionType || LocationActions.POP);
  }
}

/**
 * A Location that uses `window.location.hash`.
 */
var HashbangLocation = {

  addChangeListener: function addChangeListener(listener) {
    _listeners.push(listener);

    // Do this BEFORE listening for hashchange.
    ensureSlash();

    if (!_isListening) {
      if (window.addEventListener) {
        window.addEventListener('hashchange', onHashChange, false);
      } else {
        window.attachEvent('onhashchange', onHashChange);
      }

      _isListening = true;
    }
  },

  removeChangeListener: function removeChangeListener(listener) {
    _listeners = _listeners.filter(function (l) {
      return l !== listener;
    });

    if (_listeners.length === 0) {
      if (window.removeEventListener) {
        window.removeEventListener('hashchange', onHashChange, false);
      } else {
        window.removeEvent('onhashchange', onHashChange);
      }

      _isListening = false;
    }
  },

  push: function push(path) {
    _actionType = LocationActions.PUSH;
    window.location.hash = slashToHashbang(path);
  },

  replace: function replace(path) {
    _actionType = LocationActions.REPLACE;
    window.location.replace(window.location.pathname + window.location.search + '#' + slashToHashbang(path));
  },

  pop: function pop() {
    _actionType = LocationActions.POP;
    History.back();
  },

  getCurrentPath: function getCurrentPath() {
    return decodeURI(
    // We can't use window.location.hash here because it's not
    // consistent across browsers - Firefox will pre-decode it!
    "/" + (window.location.href.split('#!')[1] || ''));
  },

  toString: function toString() {
    return '<HashbangLocation>';
  }

};

module.exports = HashbangLocation;

slashToHashbang 함수에 주의해 주세요.

그럼 넌 그냥 하면 돼

ReactRouter.create({location: HashbangLocation})

이것으로 끝입니다:-)

언급URL : https://stackoverflow.com/questions/25086832/how-to-stop-in-browser-with-react-router

반응형