即使满足条件,主页组件也不会呈现

时间:2020-04-27 18:27:00

标签: reactjs

我正在构建一个React应用,并尝试在localhost:3000处渲染home组件。在此应用程序中,Main由App组件呈现,如果用户当前位于localhost:3000,我希望Main呈现Home组件。下面的代码是我的main.js,在其中执行条件渲染。但是,未渲染Home组件,当我使用两种方法在localhost:3000时,它只是一个空白页。我想知道如何解决此问题。谢谢!

class Main extends Component {
  render() {
    const HomePage = () => {
      return <Home />;
    };

    const WaitingRoomPage = () => {
      return <WaitingRoom />;
    };

    ......

    //1st approach
    let home;
    if (window.location.href === "http://localhost:3000") {
      home = <Home />;
    }

    //2nd approach
    const home = window.location.href === "http://localhost:3000" ? <Home /> : null;


    return (
      <div>
        <Switch>
          <Route path='/home' component={HomePage} />
          <Route path='/physics' component={PhysicsPage} />
          <Route path='/startstream' component={StartStreamPage} />
          <Route path='/stream' component={StreamPage} />
          <Route path='/signup' component={SignUpPage} />
          <Route path='/login' component={LogInPage} />
          <Route path='/profile' component={ProfilePage} />
          <Route path='/waitingroom' component={WaitingRoomPage} />
          <Route path='/streamingplaza' component={StreamingPlazaPage} />
          <Route path='/settings' component={SettingsPage} />
        </Switch>

        //Conditionally rendering Home component
        {home}

      </div>
    );
  }
}

export default Main;

1 个答案:

答案 0 :(得分:2)

localhost:3000的路径是/,而不是/home。您可以通过将path的{​​{1}}从HomePage更改为"/home"并将属性"/"(布尔值)添加到该{{1} }。 exact道具告诉路由器仅在窗口的路径正好为Route时才匹配,而不仅仅是以exact开头(如果省略,则仅"/"组件将呈现,其他都不会呈现)。如果您仍然希望支持"/"路由,则可以添加满足我上面描述的更改的另一条路由。

此后,您可以使用HomePage删除第1次和第2次尝试代码以及​​返回的组件的一部分。

这是一个完整的例子:

/home
相关问题