简体   繁体   中英

Render React JS server side using .net

I did the comments tutorial on http://reactjs.net/getting-started/tutorial.html and got it to render server side using .net mvc.

I have an existing mvc app where I rewrote a page in react. I'm trying to render it server side using .net but I get an error when it tries to render server side.

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)

Here's the code:

In my MVC view:

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

My TopicAnswers.jsx file:

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

My ReactConfig.cs file:

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

QUESTION: Why is it having a problem rendering the react file server side?

I got this error message trying to render React jsx file server side using .net:

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

My problem was that in the JSX file, I still had ComponentWillMount which called the loadAnswersFromServer. This is what you need if you are rendering client side. But once you adjust your code to render server side, you need to comment out/remove the ComponentWillMount so that it doesn't try to run the loadAnswersFromServer function on the server side.

With MVC, the data should be passed from the controller to the view and referenced in the @Html.Render("Comment", new { initialData = Model }) for the initial load.

Also, don't forget to comment out/remove the React.render( ... ) line from the JSX file.

alert is available only in browser window context. When rendering it on a server you can not call any functions that are browser related. If you are calling them, then you need to shim them so they are not failing on a server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM