gpt4 book ai didi

blazor - BL0005 - 外部参数使用 - 为什么会出现警告?

转载 作者:行者123 更新时间:2023-12-01 13:13:00 27 4
gpt4 key购买 nike

BL0005:Component parameter should not be set outside of its component.



我在一个组件中有一个组件。当我的外部组件状态发生变化时,我想更新内部组件的状态。外部组件是一个自动完成实现,改变的状态是输入文本,内部组件是自动完成项目列表,准确地说是突出显示的部分。

所以我通过它的参数改变了内部组件的状态。我收到了这个警告。为什么?

顺便说一句,代码完全按照我的预期工作。状态已同步,我匹配的文本在所有自动完成项目中突出显示。

我的猜测是更改参数可能会导致组件重新呈现自身,在我的情况下,这是完全期望和预期的行为。否则我为什么要在运行时更改组件的参数?

我在网上搜索了警告,但除此之外我没有发现任何有用的信息:
https://github.com/aspnet/AspNetCore/issues/12293

同样,看起来像我在代码中所做的那样修改参数是一种非常糟糕的做法,但同样,为什么?有没有理由我必须以不那么简单和直接的方式来做,或者有更简单和直接的方式来做到这一点?

最佳答案

好问题!

Blazor 团队的指导方针非常简单,不直接修改参数:

We want to make it hard or impossible to set a component parameter property directly. This is never correct when done in application code.



来源: https://github.com/aspnet/AspNetCore/issues/8825

但是,您必须继续寻找以找到原因。根源在于渲染系统,主要是渲染系统如何处理父子组件之间的ParameterView。

这是史蒂夫桑德森的一段话:

Every time your parent component (Index) re-renders, it's re-rendering its child (Counter) and writing a value to the Content parameter. [...]

The solution is not to mutate your [Parameter] properties directly. Doing so leads to confusion, because they are getting written from two different places which interfere with each other.



来源: https://github.com/aspnet/AspNetCore/issues/14283#issuecomment-534651201

所以基本上不直接修改参数的原因是为了避免渲染系统不同步的风险。这会导致非常微妙的错误。您的代码目前运行良好,但不能保证向 RenderTree 添加或删除组件不会导致副作用。

关于blazor - BL0005 - 外部参数使用 - 为什么会出现警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58852101/

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