React:不要根据子组件状态渲染菜单

时间:2021-02-26 01:00:44

标签: reactjs

我有一个在整个站点范围内呈现的 MenuBar,所以我在我的 App.js 中进行了设置,如下所示。我希望菜单一直呈现,除非您访问 HCA_Survey 链接。当您访问该链接时,如何使 MenuBar 组件不呈现?该链接没有导航按钮。只有用户点击电子邮件中的链接才能访问它,我不希望他们有导航栏。

我假设我需要访问它才能从 HCA_Survey 组件中更改它...但我不知道如何进行。我只需要将它重写为一个类吗?我还没有完全掌握 Hooks。

如果我手动在 true 和 false 之间更改 renderMenu 变量,它会按我的意愿工作。我只是不知道如何在访问该链接时将其更改为 false?

App.js

const App = () => {
  
  const [renderMenu, setMenu] = useState(true);
  function renderMenuBar(render) {
    setMenu(false);
  }
      
  return (
    <div className="App">
      <Row>
        {renderMenu === true && (
          <Col xs={1}>
          <MenuBar />
        </Col>
        )}
        
        <Col className="area-content">
            <Switch>
              <Route exact path="/" component={Dashboard} />
              <ProtectedRoute path="/audit" component={Audit} />
              <ProtectedRoute path="/database" component={Database} />
              <Route exact path="/hca-survey/:id/:name/:level/:audit/:client" component={HCA_Survey} />
            </Switch>
        </Col>
      </Row>
    </div>
  );
}

export default App;

1 个答案:

答案 0 :(得分:0)

如果您使用的是 react-router-dom,则可以使用 useRouteMatch 并根据它(无论是否在该路线上)重新定义 renderMenu

const App = () => {
  const isHCASurvey = useRouteMatch("/hca-survey/:id/:name/:level/:audit/:client");

  const renderMenu = !isHCASurvey;

  return (
    <div className="App">
      <Row>
        {renderMenu && (
          <Col xs={1}>
          <MenuBar />
        </Col>
        )}
        
        <Col className="area-content">
            <Switch>
              <Route exact path="/" component={Dashboard} />
              <ProtectedRoute path="/audit" component={Audit} />
              <ProtectedRoute path="/database" component={Database} />
              <Route exact path="/hca-survey/:id/:name/:level/:audit/:client" component={HCA_Survey} />
            </Switch>
        </Col>
      </Row>
    </div>
  );
}

export default App;

如果不是,则需要使用效果并侦听路线更改/初始渲染以检查安装应用程序的路线是否是要隐藏菜单的路线:< /p>

useEffect(() => {
 // modify this as needed
 const isHCASurvey = window.location.href.includes('hca-survey')
 if(isHCASurvey){
   setMenu(false)
 } else {
   setMenu(true)
 }
},[])