反应:在特定路线上隐藏组件

Yan*_*ick 3 reactjs react-router react-css-modules

React新手:

我有一个仅当用户访问特定页面时才<Header />希望隐藏的组件。

到目前为止,我设计应用程序的方式<Header />在导航时不重新渲染 Component,而是仅页面内容,因此它提供了真正的流畅体验。

我试图为每个路线重新渲染标题,这将使其易于隐藏,但是每次导航时,都会出现难看的重新渲染故障。

因此,基本上,是否有一种方法仅在进出特定路径时才重新渲染组件?

如果没有,实现该目标的最佳实践是什么?

App.js:

class App extends Component {

  render() {
    return (
      <BrowserRouter>
        <div className="App">
          <Frame>
            <Canvas />
            <Header />
            <Main />
            <NavBar />
          </Frame>
        </div>
      </BrowserRouter>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Main.js:

const Main = () => (
  <Switch>
    <Route exact activeClassName="active" path="/" component={Home} />
    <Route exact activeClassName="active" path="/art" component={Art} />
    <Route exact activeClassName="active" path="/about" component={About} />
    <Route exact activeClassName="active" path="/contact" component={Contact} />
  </Switch>
);
Run Code Online (Sandbox Code Playgroud)

Mei*_*eir 9

You could add it to all routes (by declaring a non exact path) and hide it in your specific path:

<Route path='/' component={Header} /> // note, no exact={true}
Run Code Online (Sandbox Code Playgroud)

then in Header render method:

render() {
  const {match: {url}} = this.props;

  if(url.startWith('/your-no-header-path') {
    return null;
  } else {
    // your existing render login
  }
}
Run Code Online (Sandbox Code Playgroud)


rob*_*bit 8

从 React Router 5.1 开始,有一个钩子 useLocation,它可以让你轻松访问当前位置。

import { useLocation } from 'react-router-dom'

function HeaderView() {
  let location = useLocation();
  console.log(location.pathname);
  return <span>Path : {location.pathname}</span>
}
Run Code Online (Sandbox Code Playgroud)


rwo*_*old 5

我也是React的新手,但是遇到了这个问题。react-router可接受答案的一个基本替代方法是use withRouter,它包装了您要隐藏的组件并为它提供了locationprop(以及其他)。

import { withRouter } from 'react-router-dom';    
const ComponentToHide = (props) => {
  const { location } = props;
  if (location.pathname.match(/routeOnWhichToHideIt/)){
    return null;
  }

  return (
    <ComponentToHideContent/>
  )
}

const ComponentThatHides = withRouter(ComponentToHide);
Run Code Online (Sandbox Code Playgroud)

请注意,尽管来自文档的警告:

withRouter不像React Redux的connect那样订阅位置更改来进行状态更改。而是在位置更改后从组件传播出来,然后重新渲染。这意味着withRouter不会在路由转换时重新呈现,除非其父组件重新呈现。

尽管没有这个警告,但是对于与OP非常相似的用例,这种方法似乎对我有用。

  • 从 React Router 5.1 开始,可以使用钩子 useLocation() (2认同)