【问题标题】:Blazor / Variables not updating after @onclick Task@onclick 任务后 Blazor / 变量未更新
【发布时间】:2020-10-26 21:30:22
【问题描述】:

我对编程真的很陌生,所以如果我使用了不正确的术语,我深表歉意。我正在尝试在 Blazor 应用程序中使用 Riot 的 API,但是在单击使用 API 设置值的按钮后,我在页面上显示的变量没有更新为它们所具有的值。可能是因为我实例化对象的方式。

我试图让 summoner.Namesummoner.Level 显示名称和级别,但它们在页面上是空的,即使在单击按钮之后也是如此.我已经为这两个项目添加了一个手表,并确认它们正在返回代码中的值,但不知道为什么它们没有在页面上更新。是因为 Summoner caller = new Summoner(); 这一行吗?我尝试将其设置为 null,但这会导致错误。

代码如下:

@using Newtonsoft.Json
@page "/"
@inject HttpClient http;

<h1>API Calling</h1>

<button class="btn btn-success" @onclick="@GetSummonerTask">Get Summoner</button>
<br>
<p>
    NAME: @summoner.Name
    <br>
    LEVEL: @summoner.Level
</p>


@code{

        Summoner summoner = new Summoner();

        private async Task GetSummonerTask()
        {
            SummonerInformation summonerInformation = new SummonerInformation();
            Summoner summoner = await summonerInformation.GetSummoner();
        }


        public class SummonerInformation
        {
            HttpClient client = new HttpClient();

            public async Task<Summoner> GetSummoner()
            {

                var summonerName = await client.GetAsync(new Uri("https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/weeatrocks?api_key={I have my API key here but taking out for obvious reasons}"));
                var JSON = await summonerName.Content.ReadAsStringAsync();
                Summoner summoner = JsonConvert.DeserializeObject<Summoner>(JSON);
                return summoner;

            }
        }


        public class Summoner
        {
            [JsonProperty(PropertyName = "name")]
            public string Name { get; set; }

            [JsonProperty(PropertyName = "summonerLevel")]
            public string Level { get; set; }
        }
    }

【问题讨论】:

  • 任何错误消息 javascript 或其他
  • 控制台中没有错误信息

标签: c# blazor


【解决方案1】:

您将返回分配给与类字段同名的局部变量。

private async Task GetSummonerTask()
{
    SummonerInformation summonerInformation = new SummonerInformation();
    summoner = await summonerInformation.GetSummoner(); 
   // await InvokeAsync(StateHasChanged); 
}

【讨论】:

  • 感谢您的回复!我添加了这一点,但下方有一个绿色波浪线,上面写着“CS4014:由于未等待此调用,因此在调用完成之前继续执行当前方法。考虑将'await'运算符应用于调用结果。”它似乎不起作用,在某处添加 await 会有所帮助吗?
  • 你是否放置了一个断点来检查 sumoner 变量的内容? await client.GetFromJsonAsync(... ) 将是反序列化的更好方法,但不清楚您的 API 返回什么。
  • 我有!它说的值是:召唤者:{ApiTest.Pages.Index.Summoner}召唤者。名称:“WeEatRocks”召唤者。等级:“65”
  • 召唤师召唤者 = 等待召唤师信息.GetSummoner();是你有一个局部变量的问题。这不是更新类字段。生病更新解决方案
  • 是的!就是这样!!我拿出 Summoner 并按照你写的那样拥有它并且它有效!太感谢了! await InvokeAsync 是否必要?我把它注释掉了,它还在工作。
猜你喜欢
  • 1970-01-01
  • 2019-09-27
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 2021-10-30
  • 2021-01-23
相关资源
最近更新 更多