Svelte Native中#if条件渲染失效问题求助
Svelte Native条件渲染不生效的问题修复
你的代码逻辑存在错误,导致{:else}分支永远不会被触发——不管po.id是null还是undefined,po.id !== null || po.id !== undefined这个条件的结果始终为true:
- 当
po.id为null时,po.id !== undefined成立,整个或运算返回true - 当
po.id为undefined时,po.id !== null成立,整个或运算也返回true
所以不管po.id是什么值,都会渲染第一个flexboxLayout组件,永远看不到stackLayout的内容。
修正方案
把逻辑运算符从||换成&&,或者用更简洁的po.id != null(这个写法会同时判断po.id不是null也不是undefined):
方案1:使用&&修正逻辑
{#if po.id !== null && po.id !== undefined} <flexboxLayout flexWrap="wrap" class="v-a-c t-a-c" > <label text="first" width="70%" backgroundColor="#63c3d0" class="m6"></label> <label text="second" width="70%" backgroundColor="#63c3d0" class="m6"></label> <label text="third" width="70%" backgroundColor="#63c3d0" class="m6"></label> </flexboxLayout> {:else } <stackLayout flexWrap="wrap" class="v-a-c t-a-c"> <textField bind:text="{personName}" class="m6 new-person" ></textField> <button text="add new value" on:tap="{createNewPlayer}" /> </stackLayout> {/if}
方案2:使用!= null简化判断
{#if po.id != null} <flexboxLayout flexWrap="wrap" class="v-a-c t-a-c" > <label text="first" width="70%" backgroundColor="#63c3d0" class="m6"></label> <label text="second" width="70%" backgroundColor="#63c3d0" class="m6"></label> <label text="third" width="70%" backgroundColor="#63c3d0" class="m6"></label> </flexboxLayout> {:else } <stackLayout flexWrap="wrap" class="v-a-c t-a-c"> <textField bind:text="{personName}" class="m6 new-person" ></textField> <button text="add new value" on:tap="{createNewPlayer}" /> </stackLayout> {/if}
这个逻辑错误在标准Svelte里同样存在,只是你可能没测试到po.id为null或undefined的场景,才误以为它能正常运行。修正后在Svelte Native里就能按预期切换组件显示了。
内容的提问来源于stack exchange,提问作者Shoxious
相关产品推荐
相关产品推荐

