Home > Blockchain >  How to force StateHasChanged in blazor?
How to force StateHasChanged in blazor?

Time:03-12

I have this code:

    <div >
    <SfToast ID="toast_default" @ref="ToastObj" Title="Error" Content="@a" </SfToast>
    </div>
   
@code{    
         a = "Test";
            StringBuilder b = new StringBuilder();
            b.Append("Hello ");  
            
            if (b.ToString() != "")
            {
           a = a  b;
            StateHasChanged();
            await ToastObj.ShowAsync();
            }
}

When this "ToastObj" open, I need click 2 times to refresh. I don't know why.

For example:
First Result: Test
Second Result: Test Hello
I need click two times to refresh.

CodePudding user response:

Try use InvokeAsync(StateHasChanged);

CodePudding user response:

For the future, it would be helpful to see all the code, including the SFToast component.

However, You are calling it correctly. All you have to do to Get the page to refresh is to have the code hit the "StateHasChanged()" function. I think the problem is that you have code sitting outside of any function. Consider the @code{} to act like a normal class file with a few diffrences. For example there is no "Constructor" but the first method called on creation will be the OnInitalized(). I suggest wrapping the code and making sure all variables are initialized

@code{    

      protected override void OnInitialized()
      {
            var a = "Test";
            StringBuilder b = new StringBuilder();
            b.Append("Hello ");  
            
            if (b.ToString() != "")
            {
                a = a  b;
                StateHasChanged();
                await ToastObj.ShowAsync();
            }
      }
}
  • Related