如何在React.js中使用不同的基本结构设计路由器?

我想知道我用于路由的组件的当前体系结构是否还可以,并且想知道路由是否存在任何缺陷

由于很难用语言来描述它,因此我将在下面向您展示我的代码。

Router.js

 <BrowserRouter>
   <Route path = "/home" component = {Home} />
   <Route path = "/forum" component = {Forum} />
 </BrowserRouter>

Forum.js

class Forum extends Component{
    render(){
        return(
            <div className = "forumDiv">
                <div className = "forumBodyDiv">
                    <div className = "forumLogoDiv">
                        <img
                            className = "lolLogoImg"
                            src= {LolLogo}
                            alt="cannot display" />
                    </div>
                    <ForumHeader />
                    {this.props.location.pathname === "/forum/login" ? 
                    <Login /> : 
                    this.props.location.pathname === "/forum/register" ? 
                    <Register /> :
                    <ForumPage /> }
                </div>
            </div>
        )
    }

Home.js

class Home extends Component{
    render(){
        return(
            <div className = "homeDiv">
                <TopNavigator />
                <div className = "homeBodyDiv">
                    <LeftNavigator />
                    {this.props.location.pathname === "/home/index" ? 
                    <Index /> : 
                    this.props.location.pathname === "/home/page2" ? 
                    <Page2 /> :
                    <HomePage /> }
                </div>
            </div>
        )
    }

As you can see, since Forum and Home has different base styles, I am checking the route by this.props.location.pathname and displaying the page according to my pathname. I am wondering if this is the best, most efficient way to do this. I am skeptical since I feel like all the routes should be inside the Router.js. Can someone let me know if there is a better way to do this?

谢谢

评论
绳灵秋
绳灵秋

你可以这样写

<BrowserRouter>
  <Route path = "/home" exact component = {Home} />
  <Route path = "/forum" exact component = {Forum} />
  <Route path = "/forum/login" exact component = {Login} />
  <Route path = "/forum/register" exact component = {Register} />
</BrowserRouter>

Forum.js
import {Redirect} from 'react-router-dom';

class Forum extends Component{
  render(){
    return(
        <div className = "forumDiv">
            <div className = "forumBodyDiv">
                <div className = "forumLogoDiv">
                    <img
                        className = "lolLogoImg"
                        src= {LolLogo}
                        alt="cannot display" 
                    />
                </div>
                <ForumHeader />
                <ForumPage />
            </div>
        </div>
    )
  }
}
点赞
评论