我如何在React中隐藏/查看组件

时间:2018-08-13 14:37:36

标签: reactjs react-router react-redux

我有几个组成部分。我想做的是渲染组件“ Cart”时要禁用“ App”渲染。

这是我的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,并且每当路径等于“ cart”时我都返回null,但它对我不起作用。

2 个答案:

答案 0 :(得分:1)

使用布尔变量和三元语句,例如以下超级简化示例:

const isCart = cartShowing === true

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

答案 1 :(得分:0)

我很担心这不是关于条件渲染的简单问题。

简短:不要这样想。

更长时间:如果您需要使用不同的布局渲染Cart,请在Cart内部进行渲染。作为顶层组件/容器之一,它可以在内部渲染<PageLayout /><CartList />(与其他路线一样)。

App是逻辑胶水/结构部分,不打算包含任何视觉元素。