首页 > 解决方案 > 如何在 React 中隐藏/查看组件

问题描述

我有几个组件。我想要做的是当我渲染组件“购物车”时,我想禁用“应用程序”的渲染。

这是我的 index.js

 ReactDOM.render(
<Provider store={store}>
<HashRouter>
  <App>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/categories" component={Categories} />
      <Route path="/category/:categId" component={Products} />
      <Route path="/product/:productId" component={Product} />
      <Route path="/cart" component={Cart} />
    </Switch>
  </App>
</HashRouter>
 </Provider>
 , document.getElementById('root'),
);

我想每次在 App 组件中访问 url 并且每当路径等于“购物车”时我返回 null 但它对我不起作用。

标签: reactjsreact-routerreact-redux

解决方案


使用一个布尔变量和一个三元语句,就像这个超级简化的例子:

const isCart = cartShowing === true

return isCart
    ? <Cart/>
    : <App />

推荐阅读