简体   繁体   English

根据 URL 渲染特定的 react 组件

[英]Render specific react component based on the URL

App.js应用程序.js

function App() {
  <div className="App">
    <Router>
      <Switch>
        <Route exact path="/home" component={Home} />
        <Route exact path="/search" component={Home} />
      </Switch>
    </Router>
  </div>;
}

Home.js主页.js

function Home() {
    const location = useLocation();
    return (
        <div className="home">
            <Component1 />
            {location.pathname === "/home" && <Feed />}
            {location.pathname === "/search" && <Search />}
            <Component2 />
        </div>
    );
}

This works perfectly as I want to render the Feed or Search component depending on the URL.这非常有效,因为我想根据 URL 呈现FeedSearch组件。

But, I want to know is it okay to use location.pathname or is there any better alternative?但是,我想知道可以使用location.pathname还是有更好的选择?

You could do something like:你可以这样做:

App.js应用程序.js

function App() {
  return <div className="App">
    <Router>
      <Switch>
        <Route exact path="/home" component={() => <Home showFeed/>} />
        <Route exact path="/search" component={() => <Home showSearch/>} />
      </Switch>
    </Router>
  </div>;
}

Home.js主页.js

function Home(props) {
    const location = useLocation();
    return (
        <div className="home">
            <Component1 />
            {props.showFeed && <Feed />}
            {props.showSearch && <Search />}
            <Component2 />
        </div>
    );
}

This allows you to abstract away the Home component's dependency on any routing mechanism, and simply allows you to control whether certain elements appear or not from outside this component.这允许您抽象出Home组件对任何路由机制的依赖,并且只允许您控制某些元素是否从该组件外部出现。

use home component as layout.使用home组件作为布局。 This can be highly recommended.这可以强烈推荐。 You can rename your home component as Layout .您可以将您的home组件重命名为Layout This is more flexible way.这是更灵活的方式。

function Home() {
    const location = useLocation();
    return (
        <div className="home">
            <Component1 />
             { props.children }
            <Component2 />
        </div>
    );
}

In your app.js modify like bellow在你的app.js修改如下

function App() {
  <div className="App">
    <Router>
      <Switch>
        <Route exact path="/home">
          <Home>
           <Feed />
          </Home>
         </Route>
        <Route exact path="/search">
          <Home>
           <Search/>
          </Home>
         </Route>
        </Route>
      </Switch>
    </Router>
  </div>;
}

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

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