Why doesnt the page preserve the data?

独自空忆成欢 提交于 2020-06-17 15:49:17

问题


So I'm currently looking at the Blazor example project.. The "Counter" to be more specific, and when I increment the value on the page, and then click a different tab on the webapp, let's say the "Fetch data" tab which pulls up the weather, and then I go back, the value that was incremented is back to 0.. Why is that? Why isn't it saved?

Here is the NavMenu

<div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
    <ul class="nav flex-column">
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
                <span class="oi oi-home" aria-hidden="true"></span> Home
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="counter">
                <span class="oi oi-plus" aria-hidden="true"></span> Counter
            </NavLink>
        </li>
        <li class="nav-item px-3">
            <NavLink class="nav-link" href="fetchdata">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
            </NavLink>
        </li>
    </ul>
</div>

And the Counter

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}


回答1:


This is by design. When your Counter Page Component goes out of scope it is destroyed, and when you go back, it is re-created. But you can cache its state (the count value) and read the last value when you go back to the page. You may save the state value in the local storage or session storage (JavaScript Api), which you can use directly employing the JSInterop feature of Blazor, or still better, use libraries design to work with Blazor created by the Blazor community, and even by the Blazor team (recommended)

Hope this helps...




回答2:


NOTE: This is not a duplicate of another answer. I deleted the other (identical) answer when I marked the other question as a duplicate of this one.

Components are created/destroyed as needed, even within a single page if they are displayed / hidden. Therefore, any state they hold is lost along with the component that has disappeared.

Components are designed for rendering visuals and managing interaction. They can hold some state, but not state across their own lifetimes. To achieve this you need to store the state elsewhere, in a service for example.

I wrote Fluxor to deal with this scenario: https://github.com/mrpmorris/fluxor

Someone created a video here: https://www.youtube.com/watch?v=k_c-ErPaYa8



来源:https://stackoverflow.com/questions/62238838/why-doesnt-the-page-preserve-the-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!