该项目的主要目标是获取屏幕和导航菜单中按钮的计数器状态,例如:Counter(2)
我为重现所做的操作:
我创建了一个新的 Blazor WebAssembly 项目。 使用 NuGet 安装 Fluxor。 设置状态、操作和减速器如下:
CounterState.cs:
public class CounterState
{
public int Count { get; }
public CounterState(int count)
{
Count = count;
}
}
IncrementCounterAction.cs:
public class IncrementCounterAction { }
CounterReducers.cs:
using Fluxor;
public static class CounterReducers
{
[ReducerMethod]
public static CounterState ReduceIncrementCounterAction(CounterState state, IncrementCounterAction action) =>
new CounterState(state.Count + 1);
}
在Program.cs中配置Fluxor:
using BlazorApp1;
using Fluxor;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// Configure Fluxor
builder.Services.AddFluxor(options => options
.ScanAssemblies(typeof(Program).Assembly)
.UseReduxDevTools());
await builder.Build().RunAsync();
更新了 Counter.razor 以使用 Fluxor:
@page "/counter"
@using Fluxor
@inject IState<CounterState> CounterState
@inject IDispatcher Dispatcher
<h1>Counter</h1>
<p role="status">Current count: @CounterState.Value.Count</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private void IncrementCount() => Dispatcher.Dispatch(new IncrementCounterAction());
}
更新了 NavMenu.razor 以显示计数:
@using Fluxor
@inject IState<CounterState> CounterState
<div class="top-row ps-3 navbar navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="">BlazorApp1</a>
<button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu">
<span class="navbar-toggler-icon"></span>
</button>
</div>
</div>
<div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
<nav class="flex-column">
<div class="nav-item px-3">
<NavLink class="nav-link" href="" Match="NavLinkMatch.All">
<span class="oi oi-home" aria-hidden="true"></span> Home
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="counter">
<span class="oi oi-plus" aria-hidden="true"></span> Counter (@CounterState.Value.Count)
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="fetchdata">
<span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
</NavLink>
</div>
</nav>
</div>
@code {
private bool collapseNavMenu = true;
private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null;
private void ToggleNavMenu()
{
collapseNavMenu = !collapseNavMenu;
}
}
问题: 当我运行应用程序时,出现以下错误:未处理的异常渲染组件:尝试激活“Fluxor.State”时无法解析类型“Fluxor.IFeature”的服务。
我尝试过的:
确保所有课程都是公开的。 清理并重建解决方案。 验证 Program.cs 中 Fluxor 的配置是否正确。 环境:
.NET 6.0 视觉工作室 2022 Blazor WebAssembly 任何帮助或建议将不胜感激!
我遇到了同样的错误,我忘记将 [FeatureState] 放在我的 State 类之上。