programing

Electron과 함께 리액트 라우터를 사용하는 방법

madecode 2023. 3. 4. 15:24
반응형

Electron과 함께 리액트 라우터를 사용하는 방법

보일러 플레이트를 참고하여 Electron 앱을 만들었습니다.웹 팩을 사용하여 스크립트를 번들하고 express 서버를 사용하여 스크립트를 호스트합니다.

웹 팩 구성은 이것과 거의 같고 서버 구성도 이와 같습니다.

Electron의 스크립트 로드:

mainWindow.loadURL('file://' + __dirname + '/app/index.html');

또한 index.html은 서버에서 호스팅하는 스크립트를 로드합니다.

<script src="http://localhost:3000/dist/bundle.js"></script>

나는 달린다electron index.js앱을 만들고node server웹 팩을 사용하여 스크립트를 번들하는 서버를 시작합니다.

정상적으로 동작합니다.React 컴포넌트 앱이 마운트되어 있습니다.리액트 라우터를 어떻게 통합하면 좋을까요?

브라우저 앱과 같은 방법으로 구현했습니다.다음의 에러가 표시됩니다.

[react-router] Location "/Users/arjun/Documents/Github/electron-app/app/index.html" did not match any routes

파일 경로를 경로로 사용하고 있습니다.보일러 번호판 코드를 살펴보는 것은 도움이 되지 않았다.제가 무엇을 빠뜨리고 있나요?

교환이 필요함BrowserRouter와 함께HashRouter.

import {
  HashRouter,
  Route
} from "react-router-dom";

그리고 내 안에index.jsElectron 앱의 엔트리 파일에는 다음과 같은 것이 있습니다.

<HashRouter>
  <div>
    <Route path="/" exact     component={ Home } />
    <Route path="/firstPage"  component={ FirstPage } />
    <Route path="/secondPage" component={ SecondPage } />
  </div>
</HashRouter>

그리고 모든 게 잘 풀렸어요

이유:BrowserRouter는 요구 기반 환경을 대상으로 하고 있습니다.HashRouter는 파일 기반 환경을 대상으로 합니다.

자세한 내용은 이쪽:

다른 옵션은 hashHistory를 사용하는 것입니다.실제로, 당신이 참조한 레포에서 그들이 hashHistory를 사용하고 있는 것을 알 수 있습니다.그것을 시도해서 다시 투고하는 것은 어떻습니까?

리액트 라우터 v4를 사용하고 있기 때문에 폴백하고 싶지 않습니다.HashRouter그래서 다음과 같은 것으로 해결했습니다.

import { Redirect, BrowserRouter } from 'react-router-dom';

const App = () => (
  <BrowserRouter>
    <div>
      {window.location.pathname.includes('index.html') && <Redirect to="/" />}
    </div>
  </BrowserRouter>
);

답변에서 가장 좋은 방법은 MemoryRouter를 사용하는 것입니다.MemoryRouter, worked for me : )

Switch를 사용하여 다음과 같이 기본 "/"로 설정하면 어떨까요?

<Switch>
  <Route path="/" exact component={Home}/>
  <Route path="/foo" component={Foo}/>
  <Route path="/bar" component={Bar}/>
  <Route render={() => <Redirect to="/"/>}/>
</Switch>

이렇게 하면 "/index.html"은 "/"로 리다이렉트 됩니다.

(현재) 리액트라우터 문서에는 다음과 같이 기재되어 있습니다.

일반적으로 요구에 응답하는 서버가 있는 경우 <BrowserRouter>를 사용하고 정적 파일서버를 사용하는 경우 <HashRouter>를 사용해야 합니다.

Electron 앱은 기본적으로 정적 파일 서버입니다.

Memory Router도 모든 라우팅이 앱의 React 부분 내에서 발생하는 한 작동합니다.브라우저 프로세스에서 특정 페이지로 이동하려는 경우(예: 새 창을 열고 "일반 환경설정" 페이지로 직접 이동하려는 경우)에만 해당됩니다.이 경우 HashRouter를 사용하여 다음 작업을 수행할 수 있습니다.

prefsWindow.loadURL(`file://${__dirname}/app/index.html#/general-prefs`);

(Browser 프로세스에서) MemoryRouter에서는 그렇게 할 수 없다고 생각합니다.

니케르트 말에 동의해하지만 어떤 경로 관리보다 이런 식으로 대처하는 것이 좋다고 생각합니다.

if ( window.location.pathname.includes('index.html') ) {
    location.pathname = ROUTES.ROOT;
}

, 「」에 의 종류에 따라 달라집니다.mainWindow.loadURL.

file://...

「 」를 로드했을 index.html file://: 프로토콜:

mainWindow.loadURL('file://' + path.join(__dirname, '../index.html#/home'))

'보다'를 써야 요.HashRouter:

<HashRouter>
  <Routes>
    <Route path='/home' element={<MyHomeScreen/>}>
  </Routes>
</HashRouter>

에 주의:#index.html#/home매우 중요합니다!

왜요?

쓰면 생각해 보세요.index.html/homehomeindex.html디렉토리로 이동합니다.#이를 방지하기 위해 HashRouter를 사용해야 합니다.

http://localhost:3000

「 」를 로드했을 index.html「」와 localhost:3000 이렇게 두 방법이

  • # 」와
    mainWindow.loadURL('http://localhost:3000#/home')
    
    를 사용합니다.HashRouter위와

또는

  • 를 포함하지 않습니다.# 」와
    mainWindow.loadURL('http://localhost:3000/home')
    
    를 사용합니다.BrowserRouter 이렇게요.
    <BrowserRouter>
      <Routes>
        <Route path='/home' element={<MyHomeScreen/>}>
      </Routes>
    </BrowserRouter>
    

많은 사람들이 사용하는 것을 선호한다.BrowserRouter이 "URL"로 것을 #.

언급URL : https://stackoverflow.com/questions/36505404/how-to-use-react-router-with-electron

반응형