реагировать если заявление в jsx и map - PullRequest
0 голосов
/ 04 июля 2018

у меня есть рабочий код и небольшая проблема с оператором if в функции карты, здесь код

    const SortableItem = SortableElement(CashItem);
const SortableList = SortableContainer(({items}) => {
  return (
    <div>
      {items.map((cashitem, index) => (
        <SortableItem key={`item-${index}`} 
          index={index} 
          isPayed={cashitem.isPayed}
          date={cashitem.date}
          name={cashitem.name}
          realisticVal={cashitem.realisticVal}
          realisticBalance={cashitem.realisticBalance}
          optimisticBalance={cashitem.optimisticBalance}
          optimisticVal={cashitem.optimisticVal}
          changedName={(event) => this.nameChangedHandler(event, cashitem.id)} 
          isBlocked={(event) => this.handleChangeCheckbox(event, cashitem.id)} 
          delete={(event) => this.removeItem(event, cashitem.id)} 
          addNext={(event) => this.addNext(event, cashitem)} 
          realisticChange={(event) => this.realisticBalanceChangedHandler(event, cashitem.id)}  
          optimisticChange={(event) => this.optimisticBalanceChangedHandler(event, cashitem.id)}  
          dateChangedHandler={(event) => this.dateChangedHandler(event, cashitem.id)}
         />
      ))}
    </div>
  );
});

теперь я хочу chceck, если выписка будет отображаться, только когда на карте cashitem имеет состояние виден cashitems isVisible уже имеет isVisible: true или false, я хочу сделать что-то подобное

 const SortableItem = SortableElement(CashItem);
const SortableList = SortableContainer(({items}) => {
  return (
    <div>
      {items.map((cashitem, index) => (
        if(cashitem.isVisible===true){
          <SortableItem key={`item-${index}`} 
          index={index} 
          isPayed={cashitem.isPayed}
          date={cashitem.date}
          name={cashitem.name}
          realisticVal={cashitem.realisticVal}
          realisticBalance={cashitem.realisticBalance}
          optimisticBalance={cashitem.optimisticBalance}
          optimisticVal={cashitem.optimisticVal}
          changedName={(event) => this.nameChangedHandler(event, cashitem.id)} 
          isBlocked={(event) => this.handleChangeCheckbox(event, cashitem.id)} 
          delete={(event) => this.removeItem(event, cashitem.id)} 
          addNext={(event) => this.addNext(event, cashitem)} 
          realisticChange={(event) => this.realisticBalanceChangedHandler(event, cashitem.id)}  
          optimisticChange={(event) => this.optimisticBalanceChangedHandler(event, cashitem.id)}  
          dateChangedHandler={(event) => this.dateChangedHandler(event, cashitem.id)}
         />
        }

      ))}
    </div>
  );
});

Ответы [ 4 ]

0 голосов
/ 28 мая 2019

Создайте функцию, которая обрабатывает оператор if / else и возвращает построитель jsx / html, а затем вызовите ее в функции jsx render ().

Проверьте это решение / автор: Блэр Андерсон

renderSkillSection: function(){
  if (this.state.challengeChoices.length < 0) {                               
    return this.state.challengeChoices.map((para2, i) =>
         <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
  }
  else {
    return <div>Hello world</div>
  }   
},

render: function(){
 return (<div className="skillSection">
  {this.renderSkillSection()}   
 </div>)
}
0 голосов
/ 04 июля 2018
{
  items.map((cashitem, index) => { //<== change it to curly braces

    return cashitem.isVisible && (<SortableItem key={`item-${index}`} //<== using the return keyword
      ... 
    />)

  }
}

Вместо использования скобок измените его на фигурные скобки и используйте ключевое слово return в условии if else, как указано выше

0 голосов
/ 04 июля 2018

Вы не возвращаете компонент внутри своего оператора if.

{items.map((cashitem, index) => {
    if(cashitem.isVisible===true){
        return <SortableItem key={`item-${index}`} ...otherProps/>
    }
})}

Однако, поскольку вы фильтруете свой список, почему бы не использовать метод Array.filter ?

{items.filter(cashItem => cashItem.isVisible).map((cashitem, index) => (
    <SortableItem key={`item-${index}`} ...otherProps/>
)}
0 голосов
/ 04 июля 2018

Функция стрелки, состоящая из более чем одного выражения:

  • Брекеты вокруг него
  • Явный оператор возврата

Таким образом:

(cashitem, index) => {
    if (condition) {
        return <Component />
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...