且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Svelte 应用程序错误:在视图中将字符串转换为布尔值失败

更新时间:2022-10-22 11:31:16

正如错误中所说,你只能绑定到一个标识符或成员表达式——即一个变量.

这是因为 bind 是一个双向的东西,如果你已经将 Boolean(Number(()) 应用到它,当有人改变输入时,然后 svelte 不知道如何撤消这些函数以将数据保存"回它绑定到的那个变量中.

如果您无法将状态变量更改为布尔值(更好的解决方案,如其他答案所建议的那样),您需要手动执行此双向更新.删除 bind,只需 checked={Boolean(Number(c.status))},并处理输入的 change 事件以从真/假回到1"或0",并将其保存到状态.

使用:

function handleClick(country) {country.find(c => c.name == country.name).status = (country.status == "1") ?0":1"}

handleClick(c)}/>

看到它在这个repl

中工作

In a Svelte app, I have this array of countries:

let countries = [
    {
        name:"Alegeria",
        status: "1"
    },
    {
        name:"Bulgaria",
        status :"0"
    }
]

Note the status property is a string. I iterate the array this way:

{#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}

As you can see, I try to convert the value of the status property to a boolean this by using Boolean(Number(c.status)).

Instead of the desired conversion I get the error: Can only bind to an identifier (e.g. foo) or a member expression as the REPL shows.

What am I doing wrong?

As it says in the error, you can only bind to an identifier or member expression - ie a variable.

This is because a bind is a two-way thing, and if you have applied Boolean(Number(()) to it, when someone changes that input, then svelte doesn't know how to undo those functions to 'save' the data back into that variable it's bound to.

If you can't change the status variables to be boolean (better solution, as suggested by other answers), you need to manually do this two-way updating. Drop the bind, just have checked={Boolean(Number(c.status))}, and handle the input's change event to convert from true/false back into "1" or "0", and save that to the status.

Use:

function handleClick(country) {
    countries.find(c => c.name == country.name).status = (country.status == "1") ? "0" :"1"
}

and

<Switch checked={Boolean(Number(c.status))} on:change={() => handleClick(c)}/>

See it working in this repl

登录 关闭
扫码关注1秒登录
Svelte 应用程序错误:在视图中将字符串转换为布尔值失败
发送“验证码”获取 | 15天全站免登陆