获取React路由的电子应用程序路径

问题描述 投票:0回答:1

我对React和React Routing很新,所以也许我完全走错了路。很高兴为您提供帮助!所以我有一个像这样运行的电子App:

// Define Options for Window object.
let windowOptions = {
  width: 1200,
  height: 800,
  frame: false,
  devTools: true,
};

// Define empty winobject
let elWin = {};

Electron.createApp()
.then(() => Electron.createWindow(elWin, './index.html', 'file:', windowOptions))

我正在将我的App组件加载到index.html中的容器(startView)中:

//render App
ReactDOM.render((
  <BrowserRouter>
  <App />
  </BrowserRouter>),
  document.getElementById('startView')
);

为了更容易,我将App减少到最小。所以我基本上想要的是一个初始启动视图,它稍后会保存一个登录屏幕。成功登录后,单击登录按钮将导致新的视图。这就是Reacts路由发挥作用的地方。应用程序如下所示:

const LoggedIn= () => (
  <div> New View</div>
);

const Home = (props) => (
  <div>
  <ul>
    <li><Link to="/newView"><button> Login </button></Link></li>
  </ul>
  </div>
);

class App extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
      <Switch>
        <Route path="/" exact component={Home}/>
        <Route path="/newView" component={LoggedIn}/>
      </Switch>
      </div>
    );
  }
}

export default App;

我的问题是我无法让Home组件渲染,因为我的应用程序的初始路线明显不同。删除'exact'参数有效,它会渲染Home但是路由不再适用于其他路由(/ newView),这也是有意义的。在其他路线仍然有效的情况下,我有机会在我的应用程序的初始路径上进行渲染吗?

javascript reactjs electron react-router-v4
1个回答
4
投票

我设法找到了解决方法。启动电子应用程序时访问当前窗口位置。工作良好!

import React from 'react';
import ReactDOM from 'react-dom';

import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';

const LoggedIn= () => (
   <div> New View</div>
);

const Home = (props) => (
   <div>
      <ul>
        <li><Link to="/newView"><button> Login </button></Link></li>
      </ul>
   </div>
);


const renderHomeRoute = () => {
    if (window.location.pathname.includes('index.html')) {
       return true;
    } else return false;
};

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <Switch>
          {renderHomeRoute() ? <Route path="/" component={Home} /> : ''}
          <Route path="/newView" component={About} />
        </Switch>
      </div>
    );
  }
}

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.