我正在做react-rails app.我收到了这个奇怪的错误.似乎这是反应本身的问题.这是我收到此错误的上下文:
var ChronicBox = React.createClass({
getInitialState: function(){
return {chronics: []}
},
componentWillMount: function(){
$.ajax({
// some ajax call that setsState of chronicles
});
},
render: function(){
return(
<div className="chronics">
<ChronicsList chronics={this.state.chronics.chronicsList} />
</div>
)
}
});
Run Code Online (Sandbox Code Playgroud)
和My ChronicsList看起来像:
var ChronicsList = React.createClass({
render:function(){
console.log(this.props.chronics);
var chronics = this.props.chronics.map(function(chronic){
return(
<Chronic name={chronic.name}/>
)
});
return(
<ul>
{chronics}
</ul>
)
}
});
Run Code Online (Sandbox Code Playgroud)
从日志我看到这个:
undefined
can not read property .map of undefined
Cannot read property '_currentElement' of null
Run Code Online (Sandbox Code Playgroud)
从这些我看到最初状态的时间顺序为空,因此.map不能使用.然后当ajax调用setsState时,我的ChronicBox重新渲染,而chronics包含json信息,如下所示:
{
"chronicsList": [{
"id": 1,
"name": "some allergy",
"patient_id": 2,
"created_at": "2016-02-11T19:05:33.434Z",
"updated_at": "2016-02-11T19:05:33.434Z"
}, {
"id": 2,
"name": "one more allergy",
"patient_id": 2,
"created_at": "2016-02-11T19:06:04.384Z",
"updated_at": "2016-02-11T19:06:04.384Z"
}],
}
Run Code Online (Sandbox Code Playgroud)
因此ChronForm现在定义了时间顺序.但我没有在ChronicForm中看到props.chronics的那些日志,而是我得到了错误:
Cannot read property '_currentElement' of null
Run Code Online (Sandbox Code Playgroud)
有什么方法可以解决这个问题吗?我看到这是一个反应问题,但它被关闭了.
如您所述,this.props.chronics为null,因此map不起作用.因此,react无法呈现您的组件.当数据重新加载并且chronics是一个数组时,react能够成功调用render方法; 但是当它尝试将当前的虚拟DOM树与前一个虚拟DOM树进行比较时,它会失败,因为它无法找到以前的DOM树.
解决方案是在初始加载时传递数组.因此,您必须将根组件的初始状态设置为:
getInitialState: function(){
return {
chronics: {
chronicsList: []
}
}
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17179 次 |
| 最近记录: |