【问题标题】:React.NET .NET Core 3.1 Not passing props into componentReact.NET .NET Core 3.1 不将道具传递给组件
【发布时间】:2020-02-01 22:27:39
【问题描述】:

我正在使用 MVC ASP.NET Core 3.1 和 React.NET,我遇到了这个问题。

当我渲染我的组件时,组件会渲染,但 props 始终为 null。几乎就像 Html.React 渲染方法没有正确传递值一样,请帮忙!

我只是将相关代码添加到 react 中(我的 startup.cs 有更多设置)

Startup.cs

public void ConfigureServices(IServiceCollection services) {

            services.AddJsEngineSwitcher(options => options.DefaultEngineName = ChakraCoreJsEngine.EngineName).AddChakraCore();
            services.AddReact();

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
            app.UseReact(config =>
            {
                // If you want to use server-side rendering of React components,
                // add all the necessary JavaScript files here. This includes
                // your components as well as all of their dependencies.
                // See http://reactjs.net/ for more information. Example:
                config
                    .AddScript("~/scripts/react_common/login.jsx");

                 config.SetLoadBabel(true);
            });
}

index.cshtml(或任何视图,只是尝试使用这个 HTML 扩展助手)

           @Html.React("Login", new
           {
             Test = "Test"
           }, serverOnly: true)

登录.jsx

class Login extends React.Component {
    render() {
        return <div>{this.props.Test}</div>
    }

无论我做什么,例如,它都不会显示“测试”。我需要知道为什么它没有将值传递给道具。我开始对这个问题失去理智,在我开始迁移到 .NET Core 之前它工作得很好。

更多细节(Nuget 包)

React.Asp.Net(5.1.2) React.AspNet.Middleware(5.1.2)

请帮忙。

【问题讨论】:

  • 你给@Html.ReactInitJavaScript()打电话了吗?
  • 不,我认为我不需要,因为这是服务器端渲染。但我还是试过了,还是不行。
  • 取得了更大的进展,由于某种原因,道具正在转换为 pascalCase。我怎样才能让它简单地保留现有的案例?

标签: c# reactjs asp.net-core


【解决方案1】:

默认的 JSON 序列化合约解析器设置为自动将其转换为 camelCase (React)。如果您希望它保持提供的案例 - 在 startup.cs 的 Configure 方法中,您必须覆盖此行为:

app.UseReact(...
app.UseStaticFiles();

//Ensure to place this after the UseRact statement above
ReactSiteConfiguration.Configuration.JsonSerializerSettings.ContractResolver = new DefaultContractResolver();

希望这可以帮助其他人不要发疯

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 2018-07-07
    • 2021-07-21
    • 2019-01-05
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 2019-05-13
    相关资源
    最近更新 更多