(反应)仅在满足条件的情况下如何渲染组件

时间:2020-01-18 02:56:19

标签: javascript html reactjs

我试图仅在满足条件的情况下渲染子组件,但是无论我尝试什么,都没有任何效果。我遇到各种各样的错误。

我的应用程序是商店,其中包含可供客户使用的水果列表。我只想将选择的项目渲染到他们的购物篮中。那就是Facture.js想要做的。我正在尝试检查列表中具有count > 0且为0时什么都没有的水果的数量。

现在,即使我不想要它们,它也会呈现列表中的所有内容–我知道在此实际代码中没有条件,因此它将返回所有内容。

这不应该像if块一样简单吗?


如果有帮助,这是我的完整代码结构:

App.js

import Client from "./Client";

state = { fruits : [{name: "Apple", price: "3", count: 2}, 
                    {name: "Orange", price: "2", count: 0}] }

render() { <Client fruits={this.state.fruits}/> }

// I tried this : {this.props.fruits.count > 0 ? <Factures fruits={this.props.fruits} /> : null} but it returns nothing.

Client.js

import Factures from "./Factures";
render() { <Factures fruits={this.props.fruits}/> }

Factures.js

import Facture from "./Facture";
render() {
      return this.props.fruits.map(fruit => <Facture key={fruit.nom} fruit={fruit} /> );
}

Facture.js

class Facture extends React.Component {
   render() {
      return (
         <li className='list-group-item d-flex justify-content-between small'>
            <div className=''>{this.props.fruit.name}</div>
            <div className=''>{'x' + this.props.fruit.count}</div>
         </li>
      );
   }
}

export default Facture;

2 个答案:

答案 0 :(得分:1)

您可以通过以下两种方式完成此操作:

选项A:过滤水果数组,然后将其作为道具传递到Client

此方法意味着您不需要在子组件中使用任何条件,因为您只需要传递要呈现为道具的水果即可。

// only keep fruits if fruit.count > 0
render() { <Client fruits={this.state.fruits.filter(fruit => fruit.count > 0}/> }

选项B:Facture组件中的条件渲染

此方法将检查每个水果的计数,并仅在fruit.count > 0处显示水果。

class Facture extends React.Component {
  render() {
    // if `fruit.count > 0`, render. otherwise, null
    return this.props.fruit.count > 0 ? (
      <li className="list-group-item d-flex justify-content-between small">
        <div className="">{this.props.fruit.name}</div>
        <div className="">{"x" + this.props.fruit.count}</div>
      </li>
    ) : null;
  }
}

export default Facture;

答案 1 :(得分:0)

class Facture extends React.Component {
   constructor(props) {
     super(props);
   }

   render() {
      return (
        {this.props.fruit.count > 0 && 
         <li className='list-group-item d-flex justify-content-between small'>
            <div className=''>{this.props.fruit.name}</div>
            <div className=''>{'x' + this.props.fruit.count}</div>
         </li>
        }
      );
   }
}

export default Facture;