1

是否可以在循环中执行条件?我想打印我的对象数组,(例如:订单 = [ {id:000,delivery_date:1/10/2019,纸杯蛋糕:[香草,巧克力,草莓]},...])但我只想打印后端数据库中的那些(在单独的服务器上运行)并且最近提交(日期> =订单.交付日期)

有没有办法做到这一点?

renderTableData(orders) {
          const date = new Date(); 
          return (
              <tbody>
                {orders && orders.filter(order => date => new Date(order.delivery_date)).map(item =>
                    //CONDITIONAL HERE? 
                        <tr key={item.id}>
                          <td>{new Date(item.delivery_date).toLocaleDateString()}</td>
                          <td>
                            {item.cupcakes.map((subitem =>
                                <ul>
                                <li>{subitem.base}</li>
                                <li>{subitem.frosting}</li>
                                <li>{subitem.toppings}</li>
                                </ul>
                            ))}
                          </td>
                        </tr>

                )}
              </tbody>
          );
        }
4

3 回答 3

2

使用(condtion)?"true":"false"运算符

请试试这个

 renderTableData(orders) {
              const date = new Date(); 
              return (
                  <tbody>
                    {orders && orders.map(item =>(
                            date >= item.delivery_date ? 
                            <tr key={item.id}>
                              <td>{new Date(item.delivery_date).toLocaleDateString()}</td>
                              <td>
                                {item.cupcakes.map((subitem =>
                                    <ul>
                                    <li>{subitem.base}</li>
                                    <li>{subitem.frosting}</li>
                                    <li>{subitem.toppings}</li>
                                    </ul>
                                ))}
                              </td>
                            </tr>
                          : ""
                    )) }
                  </tbody>
              );
            }
于 2020-01-08T06:25:00.963 回答
1

为什么不使用三元运算符?在返回本身内部

{ Condition ? 
   {true}
   :
   {false}
  }
于 2020-01-08T06:28:27.110 回答
0

您可以直接使用&&添加条件,而无需使用条件语句。因此,无论您喜欢什么,单个&&和条件语句都是有效的。

renderTableData(orders) {
        const date = new Date(); 
            <tbody>
              {orders && orders.map(item => (
                date >= item.delivery_date &&
                <tr key={item.id}>
                  <td>{new Date(item.delivery_date).toLocaleDateString()}</td>
                  <td>
                    {item.cupcakes.map((subitem =>
                      <ul>
                        <li>{subitem.base}</li>
                        <li>{subitem.frosting}</li>
                        <li>{subitem.toppings}</li>
                      </ul>
                    ))}
                  </td>
                </tr>
              ))}
            </tbody>
         );
       }
于 2020-01-08T06:32:24.543 回答