gpt4 book ai didi

Blazor 可选路由参数

转载 作者:行者123 更新时间:2023-12-03 14:38:53 26 4
gpt4 key购买 nike

使用 dotnet new blazor 创建新的 blazor 项目.修改 Index.cshtml :

@page "/"
@page "/{Id}"

<h1>Id = @Id</h1>

<p><a href="/">Without Id</a></p>
<p><a href="/15">With Id = 15</a></p>

@functions {
[Parameter]
public string Id { get; set; }
}

运行应用程序。

当我点击 With Id = 15链接,一切正常 - url 已更改,参数 {Id}分配给值 Id , 都好。

但是当我点击 Without Id之后的链接,url 已更改,但我的 ID 保持不变 - 等于 15。

为什么我的值没有改变?我在这里缺少什么?我怎样才能解决这个问题?

最佳答案

此行为是设计使然。
请注意,更改的 url 并不意味着当前页面已更改。以下 JavaScript 函数执行更改 url 的内部导航:

function performInternalNavigation(absoluteInternalHref: string) {
history.pushState(null, /* ignored title */ '', absoluteInternalHref);
handleInternalNavigation();
}

来源: https://github.com/aspnet/AspNetCore/blob/93127b39e824181d4f9b1a62b6fc8d10c481e2c8/src/Components/src/Microsoft.AspNetCore.Components.Browser.JS/src/Services/UriHelper.ts

调用 history.pushState 会导致 URL 栏显示“.../15”,但不会导致浏览器加载新的 url,或者导致 Blazor 重新创建索引组件。如果仅更改 URL 参数,Blazor 不会重新创建组件。由于您已经在 Index 页面上,单击“Without Id”链接不会导致 Index Component 重新呈现。而是重用了当前的 Component 实例,可惜这个实例组件的参数属性设置为 15,并且它不会被“遍历 ParameterCollection,将每个参数分配给同名属性的 AssignToProperties 方法覆盖”估计的正好。”但是 ParameterCollection 不包含 Id 参数;回想一下,这是在您点击“无 ID”后发生的。同样,最终结果是参数属性 Id 包含值 15。
来源: https://github.com/aspnet/Blazor/blob/29f925852b0a5e81e82780e0c1c32b486f7c3be6/src/Microsoft.AspNetCore.Blazor/Components/ParameterCollectionExtensions.cs

解决此问题的解决方法:
  • 像这样覆盖 SetParameters 方法:

  • public override void SetParameters(ParameterCollection parameters)
    {
    if (string.IsNullOrEmpty(parameters.GetValueOrDefault<string>("Id")))
    {
    Id = null;
    }
    base.SetParameters(parameters);
    }
  • 通过子类路由器实现自定义路由逻辑

  • 希望这可以帮助...

    关于Blazor 可选路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55732950/

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