简体   繁体   English

用React Router路由目录

[英]Route directory with React Router

I used to have my homepage in /home . 我以前在/home有主页。 I want to migrate it to the base url / . 我想将其迁移到基本URL /

When I did 当我做的时候

<Route
    path="home"         
    component={HomePage}
/>

I could access the page at localhost/home 我可以在localhost/home访问页面

If I want to use the base directory, I get a blank page, I have tried 如果我想使用基本目录,我会得到一个空白页,

<Route
    path=""         
    component={HomePage}
/>

and (just in case) 和(以防万一)

<Route
    path="/"            
    component={HomePage}
/>

The App.js is receiving empty props.children too, although I am only sending an empty string as the path name and the rest remains the same. App.js也接收到空的props.children ,尽管我只发送一个空字符串作为路径名,其余的保持不变。

What the app renders is this 该应用程序呈现的是这个

render() {
  return (
    <div>
      {this.props.children}
    </div>
  );
}

When the route is not an empty string, the props children is full of properties like key, props, type, etc 如果路线不是空字符串,则props子项将充满键,props,type等属性

If you only have one route and no other routes that code should be fine. 如果只有一条路由而没有其他路由,则该代码应该没问题。 If you have other routes then that code will start to have problems as path='/about' or path='/info' all contain '/' so the use of exact path instead is necessary, for the base route at least. 如果您还有其他路线,则该代码将开始出现问题,因为path ='/ about'或path ='/ info'全部包含'/',因此至少对于基本路线而言,必须使用精确路径。 Or you could use switch to match the first route it finds but I'll just stick to the question at hand. 或者,您也可以使用switch来匹配它找到的第一个路线,但是我只是坚持手头的问题。

//routes.js //routes.js

const App = () => (
  <Router>
    <div>
      <Route exact path="/" component={Component1}/>
      <Route exact path="/about" component={Component2}/>
    </div>
  </Router>
)

export default App; 导出默认应用程序;

//render.js //render.js

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

This should work but please reply if not. 这应该可以,但是如果没有请回复。 Take care! 照顾自己!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM