无法读取null

时间:2016-02-11 21:00:10

标签: reactjs

我正在做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>
        )
    }
});

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

从日志我看到:

undefined
can not read property .map of undefined
Cannot read property '_currentElement' of null

从这些我看到最初状态的时间顺序为空,因此.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"
    }],
}

因此ChronForm现在定义了时间顺序。但我没有在ChronicForm中看到props.chronics的那些日志,而是我得到了错误:

Cannot read property '_currentElement' of null

有什么方法可以解决这个问题吗?我看到这是一个反应问题,但它被关闭了。

3 个答案:

答案 0 :(得分:8)

如您所知,this.props.chronics为空,因此map无效。因此,react无法呈现您的组件。当数据重新加载并且chronics是一个数组时,react可以这次成功调用render方法;但是当它尝试将当前的虚拟DOM树与前一个虚拟DOM树进行比较时,它就失败了,因为它无法找到以前的DOM树。

解决方案是在初始加载时传递数组。因此,您必须将根组件的初始状态设置为:

getInitialState: function(){
  return {
    chronics: {
      chronicsList: []
    }
  }
},

答案 1 :(得分:1)

我认为当任何组件的渲染函数抛出错误时,通常会出现此错误。修复.map错误,此错误可能会消失。

您可以使用默认道具修复.map问题:

getDefaultProps: function() {
  return {
    chronics: []
  };
}

答案 2 :(得分:0)

尝试在三元操作中渲染null时遇到了同样的错误。渲染空字符串解决了这个问题:

{this.props.list.map((n) => {
    return <option value={n.key} key={n.key}>
               {n.title}{n.isDraft ? ' - (draft)' : null}
           </option>;
    })
}