【问题标题】:svelte : the on:click event fetch the API but doesn't rendersvelte : on:click 事件获取 API 但不呈现
【发布时间】:2020-11-14 05:25:18
【问题描述】:

到目前为止,我正在学习 svelte 并且喜欢它,但是在获取 api 时遇到了问题。

结果没有显示在页面上,我真的不明白为什么。当按钮被点击时,我 console.log 的数据是好的。所以问题既不是来自按钮的输入,也不是来自按钮......它只是没有在标签上显示应有的结果。 我在这里有点迷路,所以谢谢你的帮助!非常感谢:-)

<script>
    let nameOfTvshow = 'The Queen\'s Gambit'

    let searchForTvshow = getTvShow()

    async function getTvShow() {
        const res = await fetch(`http://api.tvmaze.com/search/shows?q=${nameOfTvshow}`)
        const data = await res.json()
        console.log(data)
        return data
    }
</script>

<div>
    <input type="search" name="tvshows" bind:value={nameOfTvshow} placeholder="Search for a tvshow...">
    <button on:click={getTvShow}>Search</button>
</div>

<section>
    {#await searchForTvshow}
        <p>...Looking for the show related to {nameOfTvshow}</p>
    {:then tvshows}
        <ul>
        {#each tvshows as tvshow}
            <div>
                <li><a href={tvshow.show.url}>{tvshow.show.name}</a></li>
                <div>
                    {#each tvshow.show.genres as genre}
                    <p>{ genre }</p>
                    {/each}
                </div>
                <p>&rarr;</span>{ @html tvshow.show.summary }</p>               
            </div>
        {/each}
        </ul>
    {:catch error}
        <p>It looks like something went wrong : <span>{error}</span></p>
    {/await}
</section>

【问题讨论】:

  • 你能添加响应和你现在得到的当前输出
  • 我认为问题出在变量中,然后电视节目尝试更改它

标签: svelte


【解决方案1】:

您正在调用getTvShow,但它的返回值未分配给任何变量。为了让您的内容重新呈现,您需要再次将该返回值(承诺)分配给 searchForTvshow:

<button on:click={() => searchForTvshow = getTvShow()}>Search</button>

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 2023-01-29
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2020-03-12
    相关资源
    最近更新 更多