gpt4 book ai didi

javascript - Svelte 应用程序错误 : converting string to boolean in the view fails

转载 作者:行者123 更新时间:2023-12-05 00:39:26 24 4
gpt4 key购买 nike

在 Svelte 应用程序中,我有一系列国家/地区:

let countries = [
{
name:"Alegeria",
status: "1"
},
{
name:"Bulgaria",
status :"0"
}
]
注意 status属性是一个字符串。我以这种方式迭代数组:
{#if countries.length > 0}
<table class="table">
<thead>
<tr>
<th>Country</th>
<th class="text-right">Status</th>
</tr>
</thead>
<tbody>
{#each countries as c}
<tr>
<td>{c.name}</td>
<td class="text-right"><Switch bind:checked={Boolean(Number(c.status))} /></td>
</tr>
{/each}
</tbody>
</table>
{:else}
<p class="alert alert-danger">No countries found</p>
{/if}
如您所见,我尝试转换 status 的值使用 Boolean(Number(c.status)) 将属性设置为 bool 值.
我得到了错误,而不是所需的转换: Can only bind to an identifier (e.g. ) or a member expression作为 REPL 显示。
我究竟做错了什么?

最佳答案

正如错误中所说,您只能 bind到标识符或成员表达式 - 即变量。
这是因为 bind是双向的,如果你申请了Boolean(Number(())对于它,当有人更改该输入时,svelte 不知道如何撤消这些函数以将数据“保存”回它绑定(bind)到的变量中。
如果您无法将状态变量更改为 bool 值(更好的解决方案,如其他答案所建议的那样),则需要手动执行此双向更新。放弃bind , 只要有 checked={Boolean(Number(c.status))} , 并处理输入的 change事件从真/假转换回“1”或“0”,并将其保存到状态。
利用:

function handleClick(country) {
countries.find(c => c.name == country.name).status = (country.status == "1") ? "0" :"1"
}
<Switch checked={Boolean(Number(c.status))} on:change={() => handleClick(c)}/>
看到它在 this repl 中工作

关于javascript - Svelte 应用程序错误 : converting string to boolean in the view fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63014165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com