使用 .net 渲染 React JS 服务器端

Render React JS server side using .net

我在 http://reactjs.net/getting-started/tutorial.html 上完成了评论教程,并使用 .net mvc 将其渲染到服务器端。

我有一个现有的 mvc 应用程序,我在其中重写了一个反应页面。我正在尝试使用 .net 在服务器端呈现它,但在它尝试呈现服务器端时出现错误。

Exception Details: React.Exceptions.ReactServerRenderingException: Error while rendering "TopicAnswers" to "react1": TypeError: undefined is not a function
   at React.createClass.render (Script Document [8]:80:39) ->     var answerNodes = this.props.data.map(function(answer){
   at ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext (Script Document [2]:7395:34)

代码如下:

在我的 MVC 视图中:

@Html.React("TopicAnswers", new
{
    initialAnswers = Model,
    url = Url.Action("TopicAnswers", new { id = ViewBag.TopicID }),
})

我的 TopicAnswers.jsx 文件:

var TopicAnswers = React.createClass({
    getInitialState: function(){
    alert('inside getInitialState: ' + this.props.initialAnswers);       
    return {answers: this.props.initialAnswers};
}

我的 ReactConfig.cs 文件:

ReactSiteConfiguration.Configuration
                .AddScript("~/Scripts/internal/eusVote/TopicAnswers.jsx");

问题:为什么渲染 React 文件服务器端时出现问题?

alert 仅在浏览器 window 上下文中可用。在服务器上呈现时,您不能调用任何与浏览器相关的函数。如果你正在调用它们,那么你需要填充它们,这样它们就不会在服务器上失败。

我在尝试使用 .net 呈现 React jsx 文件服务器端时收到此错误消息:

"React.Exceptions.ReactServerRenderingException: Error while rendering "TopicAnswers" to "react1": TypeError: undefined is not a function"

我的问题是在 JSX 文件中,我仍然有调用 loadAnswersFromServer 的 ComponentWillMount。如果您正在渲染客户端,这就是您所需要的。但是一旦您调整代码以呈现服务器端,您需要注释 out/remove ComponentWillMount,这样它就不会尝试 运行 服务器端的 loadAnswersFromServer 函数。

使用 MVC,数据应从控制器传递到视图并在 @Html.Render("Comment", new { initialData = Model }) 中引用以进行初始加载。

此外,不要忘记注释 out/remove JSX 文件中的 React.render( ... ) 行。