ReactJS.Net 在 MVC5 上无法解决依赖关系

ReactJS.Net on MVC5 fails to resolve dependency

我正在尝试设置一个 ASP.Net MV5 应用程序以使用 ReactJS.Net,包括服务器端渲染和捆绑。

不幸的是,它因以下异常而失败:

An exception of type 'React.TinyIoC.TinyIoCResolutionException' occurred in React.dll but was not handled in user code

Additional information: Unable to resolve type: React.ReactEnvironment

这一行出现异常:

 @Scripts.Render("~/bundles/ui-components")

这一行取自我的 _layouts.cshtml 文件。

我该如何解决我的问题?


为了提供详细信息,这里是我所做的:

  1. 在BundleConfig.cs:

        bundles.Add(new ScriptBundle("~/bundles/reactjs").Include(
                    "~/Scripts/react/react-{version}.js"));
        bundles.Add(new JsxBundle("~/bundles/ui-components")
                    .Include("~/content/ui/components/*.jsx"));
    

    我用我所有的 jsx 文件创建了一个文件夹 "Content/ui/components"(实际上只有一个 "commentsbox.jsx" 文件取自教程。

  2. 在 ReactConfig.cs 中,我删除了 WebActivatorEx.PreApplicationStartMethod 属性,因为 MVC5 不再支持此属性,这是为了 Owin 组件的利益。它仍然包含:

    public static class ReactConfig
    {
        public static void Configure()
        {
            ReactSiteConfiguration.Configuration
                .AddScript("~/content/ui/*.jsx");
        }
    }
    
  3. 在我的 Global.asax.cs 文件中,我明确调用 ReactConfig.Configure 方法来替换 WebActivatorEx.PreApplicationStartMethod 钩子:

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            ReactConfig.Configure();
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
    
  4. 我的 _layouts.cshtml 视图包含(在文件底部):

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/reactjs")
    @Scripts.Render("~/bundles/ui-components")
    @RenderSection("scripts", required: false)
    @Html.ReactInitJavaScript()
    
  5. 我的观点之一:

    @{
        ViewBag.Title = "Home Page";
    }
    
    <div id="content"></div>      
    
    @section scripts
    {
        @Html.React("CommentBox", new {}, containerId:"content")        
    }
    
  6. 最后,我的 jsx 文件:

    var CommentBox = React.createClass({
      render: function() {
        return (
            <div class="row">
                <div class="col-md-4">
                hello
                </div>
    
            </div>
        );
      }
    });
    

我终于找到问题的根源了。

实际上,错误消息具有误导性。在 ReactConfig.Configure 方法中,通配符不起作用(即 *.jsx 不起作用)。

我用这个替换了方法:

public static void Configure()
{
    ReactSiteConfiguration.Configuration
        .AddScript("~/content/ui/commentsbox.jsx").
        .AddScript("~/content/ui/comment.jsx");
}

它解决了问题。