ReactJS - ComponentDidMount 在渲染之前执行 [英] ReactJS - ComponentDidMount is executing before render

查看:101
本文介绍了ReactJS - ComponentDidMount 在渲染之前执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在反应方面遇到了一些问题.我在渲染时使用 map 函数,并且在完成之前调用了 componentDidMount 函数.

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

这里是我的代码片段

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)));
}

在field..."之前打印didMount".我该如何解决这个问题?似乎地图是异步的.

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

谢谢

推荐答案

你如何初始化你的 this.state.fields?如果您在 componentDidMount 函数中执行此操作,则 console.info("field" + field); 永远不会执行,因为该字段/数组为空.

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.

使用 setState 回调 参数在状态完成后运行代码初始化/更新.

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

这篇关于ReactJS - ComponentDidMount 在渲染之前执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆