ReactJS - ComponentDidMount is executing before re

2019-08-12 02:03发布

问题:

I´m having some problems with react. I´m using map function at render and the function componentDidMount is being called before it finish.

Here snippet of my code

componentDidMount: function() {
   console.info("didMount");
},
render: function() {
   return React.createElement("div", null, 
             this.state.fields.map(function(field) {
                console.info("field" + field);
                return React.createElement("span", null, field);
             }.bind(this)));
}

It being printed "didMount" before "field...". How can i solve this? It seems that map is async.

Thank´s

回答1:

How are you initializing your this.state.fields? If you do it in the componentDidMount function, then console.info("field" + field); never gets executed because the field/array is null.

Use the setState callback parameter to run code after the state has been initialized/updated.