【问题标题】:How can I hide/view components in React如何在 React 中隐藏/查看组件
【发布时间】:2018-08-13 14:37:35
【问题描述】:

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

这是我的 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 但它对我不起作用。

【问题讨论】:

标签: reactjs react-router react-redux


【解决方案1】:

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

const isCart = cartShowing === true

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

【讨论】:

  • 我现在试试
【解决方案2】:

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

简短:不要这样想。

更长:如果您需要使用不同的布局渲染Cart,请在Cart 内进行。作为顶级组件/容器之一,它可以在内部渲染公共(与其他路由)&lt;PageLayout /&gt;&lt;CartList /&gt;

App 是一个逻辑粘合/结构部分,不打算包含任何视觉元素。

【讨论】:

  • 虽然我的回答直接回答了这个问题,但我同意 OP 应该重新考虑他的方法,将顶级容器用于商店(?)与购物车。
猜你喜欢
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多