为了账号安全,请及时绑定邮箱和手机立即绑定

只有一个函数得到结果

只有一个函数得到结果

炎炎设计 2023-10-20 16:08:00
我有这两个函数被调用,但只有第二个函数显示在桌子上。<table className="tableList tableList--space">     <thead>{this.tableHead()}</thead>     <tbody>          {this.state.products.map((item) =>               this.tableBody(item) && this.tableBodyComplements(item)          )}     </tbody></table>功能:tableBody = (item) => (    <tr key={item.title}>        <td className="text-left">            {item.title}        </td>        <td className="text-left"> - </td>        <td className="text-right">R$ {item.price}</td>        <td className="text-center">{item.quantity}X</td>        <td className="text-right">R$ {item.total}</td>        <td className="text-left"></td>    </tr>);tableBodyComplements = (item) => (    <tr>        <td className="text-right">             {item.ComplementCategories.map(aux => {                return aux.Complements[0].title            })}         </td>        <td className="text-right"> - </td>        <td className="text-right"> - </td>        <td className="text-right">             {item.ComplementCategories.map(aux => {                return aux.Complements[0].quantity            })}         </td>        <td className="text-right">R$ {item.total}</td>        <td className="text-right"></td>    </tr>);为什么只有第二个得到了想要的结果?我不知道是否只调用了第二个,或者它与表中的第一个重叠,我怎样才能更好地理解并修复它?
查看完整描述

3 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

您当前的实现正在执行所谓的“短路”,基本上只要第一个值计算为真值,第二个值就会被返回,否则它可能会返回undefined。


要修复您的实现,它应该是这样的:


<table className="tableList tableList--space">

     <thead>{this.tableHead()}</thead>

     <tbody>

          {this.state.products.map((item) => (

               <React.Fragment>

                 {this.tableBody(item)}

                 {this.tableBodyComplements(item)}

               </React.Fragment>

            )

          )}

     </tbody>

</table>


查看完整回答
反对 回复 2023-10-20
?
森栏

TA贡献1810条经验 获得超5个赞

运算&&符实际上不会同时返回两者。如果第一个参数为 true,则返回第二个参数,否则返回 false。例如:


function Example() {

   return (

      <div>

         {"Word1" && "Word2"}

      </div>

   ) // this displays ONLY "Word2", since "Word1" is not a false value.

}


要解决此问题,请将它们包装在片段中:


 {this.state.products.map((item) => 

     <React.Fragment>

        {this.tableBody(item)}

        {this.tableBodyComplements(item)}

     </React.Fragment>

 )}


查看完整回答
反对 回复 2023-10-20
?
杨魅力

TA贡献1811条经验 获得超5个赞

在 javascript 中,任何形式的表达式


a && b

或者


a || b

只会计算为或 a。b从来没有两者兼而有之。事实上,甚至不清楚评估“两者a和b”的一般含义是什么。


在你的例子中,你想将两个元素渲染为 JSX - 所以只需将它们放在一起,包装在 a 中,Fragment这样它就是一个合法的 React 元素:


{this.state.products.map((item) =>

    <React.Fragment>

         {this.tableBody(item)}

         {this.tableBodyComplements(item)}

    </React.Fragment

)}


查看完整回答
反对 回复 2023-10-20
  • 3 回答
  • 0 关注
  • 67 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信