Component not rendering after StateHasChanged call
I have created simple NavElement component that changes a bit standard NavLink behaviour. According to log all logic works but somehow component is not re-rendered after StateHasChanged call. Relevant code looks like this:
private void OnLocationChanged(object sender, string newUriAbsolute)
{
Console.WriteLine("OnLocationChanged");
var shouldBeActiveNow = ShouldMatch(newUriAbsolute);
if (shouldBeActiveNow != IsActive)
{
IsActive = shouldBeActiveNow;
Console.WriteLine("Calling StateHasChanged");
StateHasChanged();
}
}
protected override bool ShouldRender() => true;
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
Console.WriteLine("BuildRenderTree");
builder.OpenElement(0, "li");
// Set class attribute
builder.AddAttribute(0, "class", CombineWithSpace(Class, IsActive ? ActiveClass : null));
builder.AddContent(1, ChildContent);
builder.CloseElement();
}
Component renders initialy. Later on when I click on some link logic works like expected and I get Calling StateHasChanged in browser console for two nav elements (old active and new active). But after that I can't see in logs BuildRenderTree. But when I refresh web page changes are applied.
I Just found yesterday the same problem. I was able to get it working calling it like Task.Run(StateHasChanged);
@rpedretti are you sure of this solution? Doesn't work for me :(
@arkadiuszwojcik How is OnLocationChanged called? Can you share more complete component implementation that we can use to reproduce the issue?
@danroth27 whole component code looks like this: (This code contains @rpedretti suggestion, but anyway doesn't work)
public class NavElement2 : BlazorComponent, IDisposable
{
private const string DefaultActiveClass = "active";
[Parameter]
string Class { get; set; }
[Parameter]
string Href { get; set; }
[Parameter]
string ActiveClass { get; set; }
[Parameter]
NavLinkMatch Match { get; set; }
[Parameter]
RenderFragment ChildContent { get; set; }
[Inject]
private IUriHelper UriHelper { get; set; }
private bool? _isActive;
private string _hrefAbsolute;
private bool IsActive
{
get { return (!_isActive.HasValue || _isActive.Value == false) ? false : true; }
set { _isActive = value; }
}
protected override void OnInit()
{
Console.WriteLine("OnInit");
UriHelper.OnLocationChanged += OnLocationChanged;
}
protected override void OnParametersSet()
{
Console.WriteLine("OnParametersSet");
ActiveClass = ActiveClass != null ? ActiveClass : DefaultActiveClass;
_hrefAbsolute = Href == null ? null : UriHelper.ToAbsoluteUri(Href).AbsoluteUri;
if (_isActive == null)
IsActive = ShouldMatch(UriHelper.GetAbsoluteUri());
}
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
Console.WriteLine("BuildRenderTree");
builder.OpenElement(0, "li");
// Set class attribute
builder.AddAttribute(0, "class", CombineWithSpace(Class, IsActive ? ActiveClass : null));
builder.AddContent(1, ChildContent);
builder.CloseElement();
}
public void Dispose()
{
UriHelper.OnLocationChanged -= OnLocationChanged;
}
private void OnLocationChanged(object sender, string newUriAbsolute)
{
Console.WriteLine("OnLocationChanged");
var shouldBeActiveNow = ShouldMatch(newUriAbsolute);
if (shouldBeActiveNow != IsActive)
{
IsActive = shouldBeActiveNow;
Console.WriteLine("Calling StateHasChanged");
Task.Run(StateHasChanged);
}
}
protected override bool ShouldRender() => true;
private bool ShouldMatch(string currentUriAbsolute)
{
if (EqualsHrefExactlyOrIfTrailingSlashAdded(currentUriAbsolute))
{
return true;
}
if (Match == NavLinkMatch.Prefix
&& IsStrictlyPrefixWithSeparator(currentUriAbsolute, _hrefAbsolute))
{
return true;
}
return false;
}
private bool EqualsHrefExactlyOrIfTrailingSlashAdded(string currentUriAbsolute)
{
if (string.Equals(currentUriAbsolute, _hrefAbsolute, StringComparison.Ordinal))
{
return true;
}
if (currentUriAbsolute.Length == _hrefAbsolute.Length - 1)
{
// Special case: highlight links to http://host/path/ even if you're
// at http://host/path (with no trailing slash)
//
// This is because the router accepts an absolute URI value of "same
// as base URI but without trailing slash" as equivalent to "base URI",
// which in turn is because it's common for servers to return the same page
// for http://host/vdir as they do for host://host/vdir/ as it's no
// good to display a blank page in that case.
if (_hrefAbsolute[_hrefAbsolute.Length - 1] == '/'
&& _hrefAbsolute.StartsWith(currentUriAbsolute, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
private string CombineWithSpace(string str1, string str2)
=> str1 == null ? str2
: (str2 == null ? str1 : $"{str1} {str2}");
private static bool IsStrictlyPrefixWithSeparator(string value, string prefix)
{
var prefixLength = prefix.Length;
if (value.Length > prefixLength)
{
return value.StartsWith(prefix, StringComparison.Ordinal)
&& (
// Only match when there's a separator character either at the end of the
// prefix or right after it.
// Example: "/abc" is treated as a prefix of "/abc/def" but not "/abcdef"
// Example: "/abc/" is treated as a prefix of "/abc/def" but not "/abcdef"
prefixLength == 0
|| !char.IsLetterOrDigit(prefix[prefixLength - 1])
|| !char.IsLetterOrDigit(value[prefixLength])
);
}
else
{
return false;
}
}
}
@danroth27 Don't know if that is relevant but I use this NavElement2 as part of MainLayout. Is it releated somehow?
@danroth27 I have more info on this issue. When I converted this class to Razor view template everything work as expected. I didn't change any code I just created NavElement2.cshtml file copy-past above code, removed BuildRenderTree method and adding rendering code on very top:
<li class=@(IsActive ? "active" : null)>
@ChildContent
</li>
I think in protected override void BuildRenderTree(RenderTreeBuilder builder) {..} you need to call base.BuildRenderTree(builder) first
Comment by Kaffeegangster worked!
I think in protected override void BuildRenderTree(RenderTreeBuilder builder) {..} you need to call base.BuildRenderTree(builder) first
I think forcing to call the base is a bad idea, because the component lifecycle can be broken, as demonstrated here, and it doesn't allow to redefine the returned render tree in a sub-class component.
Thanks for contacting us, @arkadiuszwojcik. As there have been many changes in this area since you've filed this issue, we're closing this. If you happen to face this issue with the most recent Blazor release please file a new issue.