尝试访问数组后,React 组件返回无法读取 null 的 属性 '__reactInternalInstance$

React component returning cannot read property '__reactInternalInstance$ of null after trying to access array

这是有问题的组件。

const UserList = React.createClass({
  render: function(){
    let theList;
    if(this.props.data){
      theList=this.props.data.map(function(user, pos){
        return (
          <div className="row user">
            <div className="col-xs-1">{pos}</div>
            <div className="col-xs-5">{user.username}</div>
            <div className="col-xs-3">{user.recent}</div>
            <div className="col-xs-3">{user.alltime}</div>
          </div>
        );
      }, this);
    } else {
     theList = <div>I don't know anymore</div>;
    }
    console.log(theList);
    return (
      theList
    );
  }
});

每当我尝试 return {theList} 时,我都会收到 Cannot read 属性 '__reactInternalInstance$mincana79xce0t6kk1s5g66r' of null 错误.但是,如果我用静态 html 替换 {theList},console.log 会打印出我想要的正确对象数组。根据答案,我尝试 return {theList} 和 theList 但这没有帮助。

在这两种情况下,console.log 首先打印出 [],我认为这是因为 componentDidMount 包含我的 ajax 从服务器获取 json 的调用并且在首先渲染()。我试过检查 this.props.data 为空但无济于事。

如果有帮助,这里是父组件:

const Leaderboard = React.createClass({
  getInitialState: function(){
    return ({data: [], mode: 0});
  },
  componentDidMount: function(){
    $.ajax({
      url: 'https://someurlthatreturnsjson',
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('https://someurlthatreturnsjson', status, err.toString());
      }.bind(this)
    });
  },
  render: function(){
    return (
      <div className="leaderboard">
        <div className="row titleBar">
          <img src="http://someimage.jpg"></img>Leaderboard
        </div> 
        <HeaderBar />
        <UserList data={this.state.data}/>
      </div>
    );
  }
}); 

if语句有个小问题:

if(this.props.data !== []){

应该是:

if(this.props.data){

this.props.data为null,如果ajax调用returns为null。或者代码可以更详细。

const data = this.props.data;
if(data && data.constructor === Array && data.length > 0) {

不确定这是否是您想要的方式,但它适合我。

编辑:

const UserList = React.createClass({
  render: function() {
    if(this.props.data){
      return this.props.data.map(function(user, pos){
        return (
          <li> className="row user">
            <span>{pos}</span>
            <span>{user.username}</span>
            <span>{user.recent}</span>
            <span>{user.alltime}</span>
          </li>
        );
      });
    } else {
      return <li>I don't know anymore</li>;
    }
  }
});
return (
  {theList}
)

应该只是

return theList

因为此时你不在 JSX 中。你在那里做什么将被解释为

return {
  theList: theList
}

这是 ES6 shorthand 属性语法。

啊好的,这里有一些有趣的问题,但你太接近了。最重要的是,对于 React,您必须始终 return 一个单一的顶级元素(例如 div)。所以,你的变量 theList 实际上是一个 div 的数组。你不能直接return。但是你可以 return 如果它被包裹在单亲 div.

const mockData = [
 {
   username: 'bob',
    recent: 'seven',
    alltime: 123,
  },
 {
   username: 'sally mae',
    recent: 'seven',
    alltime: 133999,
  },
];

var $ = {
 ajax(opt) {
   setTimeout(() => {
     opt.success(mockData);
    }, 200);
  }
}

const UserList = React.createClass({
  render: function(){
   let theList;
    if (this.props.data && this.props.data.length) {
      theList = this.props.data.map(function(user, pos){
        return (
          <div key={user.username} className="row user">
            <div className="col">{pos}</div>
            <div className="col">{user.username}</div>
            <div className="col">{user.recent}</div>
            <div className="col">{user.alltime}</div>
          </div>
        );
      });
    } else {
      theList = <div>There is NO data</div>;
    }
    
    return <div>{theList}</div>;
  }
});

const Leaderboard = React.createClass({
  getInitialState: function(){
    return ({data: [], mode: 0});
  },
  componentDidMount: function(){
    $.ajax({
      url: 'https://someurlthatreturnsjson',
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('https://someurlthatreturnsjson', status, err.toString());
      }.bind(this)
    });
  },
  render: function(){
    return (
      <div className="leaderboard">
        <UserList data={this.state.data}/>
      </div>
    );
  }
}); 

ReactDOM.render(
  <Leaderboard/>,
  document.getElementById('container')
);
.col {
  width: 200px;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>

稍微解释一下fiddle。别担心看起来很奇怪的 var $ 东西,我只是去掉了 jQuery 的 ajax 方法,这样我就可以在 200 毫秒后 return 一些假数据。

此外,对我来说,当我 运行 时,jsfiddle 给了我一个 'bad config' 消息,但我关闭了消息,结果就在那里。不知道那是什么。

访问不存在的嵌套状态也可能导致错误:

我缺乏发表评论的声誉,因此添加一个答案以备将来使用 -- 我 运行 出于不同的原因进入同一问题。显然,该错误是由较早的错误触发的,该错误会抛出反应的内部状态,但该错误会以某种方式被捕获。 github issue #8091

在我的例子中,我试图访问 属性 的状态,在将 属性 移动到 redux 存储后不存在该状态:

// original state
state: {
  files: [],
  user: {},
}
// ... within render function:
<h1> Welcome {this.state.user.username} </h1>

我随后将用户移动到 redux 存储并从状态中删除了行 //修改后的状态 状态: { 文件: [], } // ... 在渲染函数中(忘记修改):

<h1> Welcome {this.state.user.username} </h1>

这引发了神秘错误。通过修改渲染以调用 this.props.user.username 清除了所有内容。

我在渲染无状态组件时遇到此错误,并决定在使用基本 dom 操作渲染后删除反应根元素(包装 div)。

结论:注意这一点,最好不要这样做。